生活随笔
收集整理的這篇文章主要介紹了
C# EXCEL的帮助类,仅使用NPOI,不用安装Office
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
NPOI相關DLL,直接上Nuget獲取
這里作為筆記記錄一下~
using System
;
using System
.Collections
.Generic
;
using System
.Linq
;
using System
.Text
;
using System
.Threading
.Tasks
;
using NPOI
.SS
.UserModel
;
using NPOI
.HSSF
.UserModel
;
using NPOI
.XSSF
.UserModel
;
using System
.Collections
;
using System
.IO
;
using System
.Data
;
using System
.Windows
.Forms
;namespace Common
.basefunc
{public static class ExcelHelper{#region 輔助方法public static string GetSaveFilePath(){SaveFileDialog saveFileDig
= new SaveFileDialog();saveFileDig
.Filter
= "Excel Office97-2003(*.xls)|*.xls|Excel Office2007及以上(*.xlsx)|*.xlsx";saveFileDig
.FilterIndex
= 0;saveFileDig
.OverwritePrompt
= true;string dir
= Environment
.GetFolderPath(Environment
.SpecialFolder
.DesktopDirectory
);saveFileDig
.InitialDirectory
= dir
;string filePath
= null;if (saveFileDig
.ShowDialog() == DialogResult
.OK
){filePath
= saveFileDig
.FileName
;}return filePath
;}public static string GetOpenFilePath(){OpenFileDialog ofd
= new OpenFileDialog();ofd
.Title
= "請選擇要打開的文件";ofd
.Multiselect
= true;ofd
.InitialDirectory
= @"C:\Users\Administrator\Desktop";ofd
.Filter
= "Excel文件(.xls)|*.xls|Excel文件(.xlsx)|*.xlsx";ofd
.ShowDialog();string filePath
= ofd
.FileName
;return filePath
;}public static bool GetIsCompatible(string filePath
){return filePath
.EndsWith(".xls", StringComparison
.OrdinalIgnoreCase
);}public static IWorkbook CreateWorkbook(bool isCompatible
){if (isCompatible
){return new HSSFWorkbook();}else{return new XSSFWorkbook();}}public static IWorkbook CreateWorkbook(bool isCompatible
, Stream stream
){if (isCompatible
){return new HSSFWorkbook(stream
);}else{return new XSSFWorkbook(stream
);}}#region 傳入一個文件路徑,返回一個IWorkbook對象public static IWorkbook CreateWorkbook(string filepath
){IWorkbook workbook
= null;bool isCompatible
= ExcelHelper
.GetIsCompatible(filepath
);using (FileStream fs
= File
.Open(filepath
, FileMode
.Open
,FileAccess
.Read
, FileShare
.ReadWrite
)){workbook
= ExcelHelper
.CreateWorkbook(isCompatible
, fs
);fs
.Close();}return workbook
;}#endregion#region 打開一個excel文件,設置單元格的值,再保存文件public static bool SetCellValue(String ExcelPath
, String sheetname
, int column
, int row
, String value){bool returnb
= false;try{IWorkbook wk
= null;bool isCompatible
= ExcelHelper
.GetIsCompatible(ExcelPath
);using (FileStream fs
= File
.Open(ExcelPath
, FileMode
.Open
,FileAccess
.Read
, FileShare
.ReadWrite
)){wk
= ExcelHelper
.CreateWorkbook(isCompatible
, fs
);fs
.Close();}ISheet sheet
= wk
.GetSheetAt(0);ICell cell
= sheet
.GetRow(row
).GetCell(column
);cell
.SetCellValue(value);using (FileStream fileStream
= File
.Open(ExcelPath
,FileMode
.OpenOrCreate
, FileAccess
.ReadWrite
)){wk
.Write(fileStream
);fileStream
.Close();}returnb
= true;}catch (Exception){returnb
= false;throw;}return returnb
;}#endregion#region 打開一個文件,讀取excel文件某個單元格的值(多少行,多少列)public static String GetCellValue(string ExcelPath
, String sheetname
, int column
, int row
){String returnStr
= null;try{IWorkbook wk
= null;bool isCompatible
= ExcelHelper
.GetIsCompatible(ExcelPath
);using (FileStream fs
= File
.Open(ExcelPath
, FileMode
.Open
,FileAccess
.Read
, FileShare
.ReadWrite
)){wk
= ExcelHelper
.CreateWorkbook(isCompatible
, fs
);fs
.Close();}ISheet sheet
= wk
.GetSheetAt(0);ICell cell
= sheet
.GetRow(row
).GetCell(column
);returnStr
= cell
.ToString();}catch (Exception){returnStr
= "Exception";throw;}return returnStr
;}#endregion#region 打開一個文件,刪除多少以后的數據(是刪除,不是清空數據)public static void DelRowsData(string fileMatchPath
, int startRowIndex
){IWorkbook wk
= null;bool isCompatible
= ExcelHelper
.GetIsCompatible(fileMatchPath
);using (FileStream fs
= File
.Open(fileMatchPath
, FileMode
.Open
,FileAccess
.Read
, FileShare
.ReadWrite
)){wk
= ExcelHelper
.CreateWorkbook(isCompatible
, fs
);fs
.Close();}ISheet sheet
= wk
.GetSheetAt(0);for (int i
= startRowIndex
; i
<= sheet
.LastRowNum
; i
++){if (sheet
.GetRow(i
) == null){i
++;continue;}sheet
.RemoveRow(sheet
.GetRow(i
));}MemoryStream stream
= new MemoryStream();wk
.Write(stream
);var buf
= stream
.ToArray();using (FileStream fs
= new FileStream(fileMatchPath
, FileMode
.Create
, FileAccess
.Write
)){fs
.Write(buf
, 0, buf
.Length
);fs
.Flush();}}#endregionprivate static ICellStyle GetCellStyle(IWorkbook workbook
){ICellStyle style
= workbook
.CreateCellStyle();style
.FillPattern
= FillPattern
.SolidForeground
;style
.FillForegroundColor
= NPOI
.HSSF
.Util
.HSSFColor
.Grey25Percent
.Index
;return style
;}public static void PrintTwoArrayTest(object[,] array
){Console
.WriteLine("============測試打印二維數組==============");int row
= array
.GetLength(0);int column
= array
.GetLength(1);for (int r
= 0; r
< row
; r
++){for (int c
= 0; c
< column
; c
++){if (array
[r
, c
] != null){string value = array
[r
, c
].ToString();Console
.Write($
"{value} |");}}Console
.WriteLine();}}public static string[,] GetMatchArray(string[,] refArray
, string[,] matchArray
, int refColumn01
, int refColumn02
, int refColTarget01
, int matchColumn01
, int matchColumn02
, int matchColTarget01
){Console
.WriteLine("============遍歷2個二維數,匹配替換==============");int row
= refArray
.GetLength(0);int column
= matchArray
.GetLength(1);int row02
= matchArray
.GetLength(0);int iMatch
= 0;for (int r
= 0; r
< row
; r
++){string value01
= refArray
[r
, refColumn01
];string value02
= refArray
[r
, refColumn02
];if (value01
!= null && value02
!= null){if (value01
.Length
> 0 | value02
.Length
> 0){for (int r02
= 0; r02
< row02
; r02
++){string match01
= matchArray
[r02
, matchColumn01
];string match02
= matchArray
[r02
, matchColumn02
];if (value01
== match01
&& value02
== match02
){matchArray
[r02
, matchColTarget01
] = refArray
[r
, refColTarget01
];iMatch
++;Console
.WriteLine($
"匹配了{iMatch}次");}}}}}return matchArray
;}public static string[,] GetMatchArray(string[,] refArray
, string[,] matchArray
, int refColumn01
, int refColTarget01
, int matchColumn01
, int matchColTarget01
){Console
.WriteLine("============遍歷2個二維數,匹配替換==============");int row
= refArray
.GetLength(0);int column
= matchArray
.GetLength(1);int row02
= matchArray
.GetLength(0);int iMatch
= 0;for (int r
= 0; r
< row
; r
++){string value01
= string.Empty
;value01
= refArray
[r
, refColumn01
];if (value01
!= null){if (value01
.Length
> 0){for (int r02
= 0; r02
< row02
; r02
++){string match01
= string.Empty
;match01
= matchArray
[r02
, matchColumn01
];if (value01
== match01
){matchArray
[r02
, matchColTarget01
] = refArray
[r
, refColTarget01
];iMatch
++;Console
.WriteLine($
"匹配了{iMatch}次");}}}}}return matchArray
;}public static string[,] GetMatchArray(string[,] matchArray
, int refColumn01
, int refColumn02
, string sValue
){Console
.WriteLine("============遍歷2個二維數,匹配替換==============");int row
= matchArray
.GetLength(0);int column
= matchArray
.GetLength(1);int iMatch
= 0;for (int r
= 0; r
< row
; r
++){string value01
= matchArray
[r
, refColumn01
];string value02
= matchArray
[r
, refColumn02
];try{int i01
= Convert
.ToInt32(value01
);int i02
= Convert
.ToInt32(value02
);if (i01
>= i02
){matchArray
[r
, refColumn02
] = sValue
+ $
"(數量:{value02})";}}catch{}}return matchArray
;}#region 打開excel文件,獲取某一行的數據public static ArrayList GetRowData(string filepath
, int sheet_Number
, int iRow
){ArrayList arrayList
= new ArrayList();bool isCompatible
= ExcelHelper
.GetIsCompatible(filepath
);using (FileStream fsRead
= File
.OpenRead(filepath
)){IWorkbook workbook
= ExcelHelper
.CreateWorkbook(isCompatible
, fsRead
);ISheet sheet
= workbook
.GetSheetAt(sheet_Number
- 1);IRow currentRow
= sheet
.GetRow(iRow
- 1);for (int c
= 0; c
< currentRow
.LastCellNum
; c
++){ICell cell
= currentRow
.GetCell(c
);string value = string.Empty
;if (cell
!= null){value = cell
.ToString(); arrayList
.Add(value);}}return arrayList
;}}#endregionpublic static ArrayList GetDataIndexs(string filepath
, int sheet_Number
, int iRow
, string s1
, string s2
, string s3
){ArrayList arrayList
= new ArrayList();bool isCompatible
= ExcelHelper
.GetIsCompatible(filepath
);using (FileStream fsRead
= File
.OpenRead(filepath
)){IWorkbook workbook
= ExcelHelper
.CreateWorkbook(isCompatible
, fsRead
);ISheet sheet
= workbook
.GetSheetAt(sheet_Number
- 1);IRow currentRow
= sheet
.GetRow(iRow
- 1);for (int c
= 0; c
< currentRow
.LastCellNum
; c
++){ICell cell
= currentRow
.GetCell(c
);string value = string.Empty
;if (cell
!= null){value = cell
.ToString(); if (value == s1
| value == s2
|| value == s3
){arrayList
.Add(c
);}}}Console
.WriteLine("==========測試打印索引值============");foreach (var a
in arrayList
){Console
.WriteLine($
"{a} |");}return arrayList
;}}public static int GetDataIndex(string filepath
, int sheet_Number
, int iRow
, string sValue
){int i
= 0;bool isCompatible
= ExcelHelper
.GetIsCompatible(filepath
);using (FileStream fsRead
= File
.OpenRead(filepath
)){IWorkbook workbook
= ExcelHelper
.CreateWorkbook(isCompatible
, fsRead
);ISheet sheet
= workbook
.GetSheetAt(sheet_Number
- 1);IRow currentRow
= sheet
.GetRow(iRow
- 1);for (int c
= 0; c
< currentRow
.LastCellNum
; c
++){ICell cell
= currentRow
.GetCell(c
);string value = string.Empty
;if (cell
!= null){value = cell
.ToString(); if (value == sValue
){i
= c
;}}}}return i
;}public static Dictionary
<string, int> GetDataDictionary(string filepath
, int sheet_Number
, int iRow
){Dictionary
<string, int> DataDict
= new Dictionary<string, int>();bool isCompatible
= ExcelHelper
.GetIsCompatible(filepath
);using (FileStream fsRead
= File
.OpenRead(filepath
)){IWorkbook workbook
= ExcelHelper
.CreateWorkbook(isCompatible
, fsRead
);ISheet sheet
= workbook
.GetSheetAt(sheet_Number
- 1);IRow currentRow
= sheet
.GetRow(iRow
- 1);for (int c
= 0; c
< currentRow
.LastCellNum
; c
++){ICell cell
= currentRow
.GetCell(c
);string value = string.Empty
;if (cell
!= null){value = cell
.ToString(); if (!DataDict
.ContainsKey(value)){if (value == "*預計交貨日期" | value == "預計交貨日期"){value = "*預計交貨日期";}DataDict
.Add(value, c
);}else{if (filepath
.Contains("銷售訂單")) {if (value == "備注") {DataDict
.Add("收貨地址", c
);}}}}}return DataDict
;}}public static Dictionary
<string, string> GetDataDictionary(string filepath
, int sheet_Number
, int iRow
, string strColumnKey
, string strColumnValue
){Dictionary
<string, int> dic
= GetDataDictionary(filepath
, 1, iRow
);int iColumnKey
= dic
[strColumnKey
];int iColumnValue
= dic
[strColumnValue
];Dictionary
<string, string> DataDict
= new Dictionary<string, string>();bool isCompatible
= ExcelHelper
.GetIsCompatible(filepath
);using (FileStream fsRead
= File
.OpenRead(filepath
)){IWorkbook workbook
= ExcelHelper
.CreateWorkbook(isCompatible
, fsRead
);ISheet sheet
= workbook
.GetSheetAt(sheet_Number
- 1);for (int i
= 0; i
<= sheet
.LastRowNum
; i
++){IRow rowdata
= sheet
.GetRow(i
);ICell cellKey
= rowdata
.GetCell(iColumnKey
);ICell cellValue
= rowdata
.GetCell(iColumnValue
);if (cellKey
!= null && cellValue
!= null){if (!DataDict
.ContainsKey(cellKey
.ToString())){string strCellKey
= cellKey
.ToString();string strCellValue
= cellValue
.ToString();DataDict
.Add(strCellKey
, strCellValue
);}}}return DataDict
;}}#region 根據一個文件,獲取一個Excel文件的最大行數和列數(不成熟不建議用)public static Array GetRowCountAndColumnCount(string filepath
, int sheet_number
){int rowMaxCount
= 0;int columnMaxCount
= 0;FileStream readStream
= null;try{if (!string.IsNullOrEmpty(filepath
) && sheet_number
> 0){readStream
= new FileStream(filepath
, FileMode
.Open
, FileAccess
.Read
);bool isCompatible
= GetIsCompatible(filepath
);IWorkbook workbook
= CreateWorkbook(isCompatible
, readStream
);ISheet sheet
= workbook
.GetSheetAt(sheet_number
- 1);if (sheet
!= null){rowMaxCount
= sheet
.LastRowNum
+ 1; for (int c
= 0; c
<= sheet
.LastRowNum
; c
++){IRow row
= sheet
.GetRow(c
);
#pragma warning disable CS1525 if (row
!= null && row
.LastCellNum
> -1)
#pragma warning restore CS1525 {columnMaxCount
= row
.LastCellNum
;}}}}}catch (Exception e
){Console
.WriteLine(e
);throw;}finally{if (readStream
!= null){readStream
.Close();}}int[] array
= new int[2];array
[1] = rowMaxCount
;array
[2] = columnMaxCount
;return array
;}#endregionpublic static string[,] ToTwoArray(string filepath
, int arrayRowNnmber
, int arrayColumnNumber
, int sheet_Number
){string[,] array
= new string[arrayRowNnmber
, arrayColumnNumber
];bool isCompatible
= ExcelHelper
.GetIsCompatible(filepath
);using (FileStream fsRead
= File
.OpenRead(filepath
)){IWorkbook workbook
= ExcelHelper
.CreateWorkbook(isCompatible
, fsRead
);ISheet sheet
= workbook
.GetSheetAt(sheet_Number
- 1); int rowCount
= sheet
.LastRowNum
;if (!isCompatible
){rowCount
= rowCount
- 2;}for (int r
= 0; r
<= rowCount
; r
++){IRow currentRow
= sheet
.GetRow(r
); Console
.Write($
"第{r}行有{currentRow.LastCellNum}列有數據:--->");for (int c
= 0; c
< currentRow
.LastCellNum
; c
++){ICell cell
= currentRow
.GetCell(c
);string value = string.Empty
;if (cell
!= null){value = cell
.ToString(); }Console
.Write($
"{value} |");array
[r
, c
] = value;}Console
.WriteLine();}return array
;}}private static DataTable GetDataTableFromSheet(ISheet sheet
, int headerRowIndex
){DataTable table
= new DataTable();IRow headerRow
= sheet
.GetRow(headerRowIndex
);int cellCount
= headerRow
.LastCellNum
;for (int i
= headerRow
.FirstCellNum
; i
< cellCount
; i
++){if (headerRow
.GetCell(i
) == null || headerRow
.GetCell(i
).StringCellValue
.Trim() == ""){cellCount
= i
+ 1;break;}DataColumn column
= new DataColumn(headerRow
.GetCell(i
).StringCellValue
);table
.Columns
.Add(column
);}for (int i
= (headerRowIndex
+ 1); i
<= sheet
.LastRowNum
; i
++){IRow row
= sheet
.GetRow(i
);if (row
!= null && !string.IsNullOrEmpty(row
.Cells
[0].StringCellValue
)){DataRow dataRow
= table
.NewRow();for (int j
= row
.FirstCellNum
; j
< cellCount
; j
++){if (row
.GetCell(j
) != null){dataRow
[j
] = row
.GetCell(j
).ToString();}}table
.Rows
.Add(dataRow
);}}return table
;}#endregion#region 公共導出方法public static string ExportToExcel(DataSet sourceDs
, string filePath
= null){if (string.IsNullOrEmpty(filePath
)){filePath
= GetSaveFilePath();}if (string.IsNullOrEmpty(filePath
)) return null;bool isCompatible
= GetIsCompatible(filePath
);IWorkbook workbook
= CreateWorkbook(isCompatible
);ICellStyle cellStyle
= GetCellStyle(workbook
);for (int i
= 0; i
< sourceDs
.Tables
.Count
; i
++){DataTable table
= sourceDs
.Tables
[i
];string sheetName
= "result" + i
.ToString();ISheet sheet
= workbook
.CreateSheet(sheetName
);IRow headerRow
= sheet
.CreateRow(0);foreach (DataColumn column
in table
.Columns
){ICell cell
= headerRow
.CreateCell(column
.Ordinal
);cell
.SetCellValue(column
.ColumnName
);cell
.CellStyle
= cellStyle
;}int rowIndex
= 1;foreach (DataRow row
in table
.Rows
){IRow dataRow
= sheet
.CreateRow(rowIndex
);foreach (DataColumn column
in table
.Columns
){dataRow
.CreateCell(column
.Ordinal
).SetCellValue((row
[column
] ?? "").ToString());}rowIndex
++;}}FileStream fs
= new FileStream(filePath
, FileMode
.OpenOrCreate
, FileAccess
.ReadWrite
);workbook
.Write(fs
);fs
.Dispose();workbook
= null;return filePath
;}public static string[] GetSheetName(string filePath
){int sheetNumber
= 0;var file
= new FileStream(filePath
, FileMode
.Open
, FileAccess
.Read
);if (filePath
.IndexOf(".xlsx") > 0){var xssfworkbook
= new XSSFWorkbook(file
);sheetNumber
= xssfworkbook
.NumberOfSheets
;string[] sheetNames
= new string[sheetNumber
];for (int i
= 0; i
< sheetNumber
; i
++){sheetNames
[i
] = xssfworkbook
.GetSheetName(i
);}return sheetNames
;}else if (filePath
.IndexOf(".xls") > 0){var hssfworkbook
= new HSSFWorkbook(file
);sheetNumber
= hssfworkbook
.NumberOfSheets
;string[] sheetNames
= new string[sheetNumber
];for (int i
= 0; i
< sheetNumber
; i
++){sheetNames
[i
] = hssfworkbook
.GetSheetName(i
);}return sheetNames
;}return null;}public static DataTable ExcelToDataTable(string filePath
, string sheetName
){string outMsg
= "";var dt
= new DataTable();string fileType
= Path
.GetExtension(filePath
).ToLower();try{ISheet sheet
= null;FileStream fs
= new FileStream(filePath
, FileMode
.Open
, FileAccess
.Read
);if (fileType
== ".xlsx"){XSSFWorkbook workbook
= new XSSFWorkbook(fs
);sheet
= workbook
.GetSheet(sheetName
);if (sheet
!= null){dt
= GetSheetDataTable(sheet
, out outMsg
);}}else if (fileType
== ".xls"){HSSFWorkbook workbook
= new HSSFWorkbook(fs
);sheet
= workbook
.GetSheet(sheetName
);if (sheet
!= null){dt
= GetSheetDataTable(sheet
, out outMsg
);}}}catch (Exception e
){Console
.WriteLine(e
.Message
);}return dt
;}private static int sheetCellNumMax
= 12;private static DataTable GetSheetDataTable(ISheet sheet
, out string strMsg
){strMsg
= "";DataTable dt
= new DataTable();string sheetName
= sheet
.SheetName
;int startIndex
= 0;int lastIndex
= sheet
.LastRowNum
;int cellCount
= 0;IRow maxRow
= sheet
.GetRow(0);for (int i
= startIndex
; i
<= lastIndex
; i
++){IRow row
= sheet
.GetRow(i
);if (row
!= null && cellCount
< row
.LastCellNum
){cellCount
= row
.LastCellNum
;maxRow
= row
;}}try{for (int i
= 0; i
< sheetCellNumMax
; i
++){dt
.Columns
.Add(Convert
.ToChar(((int)'A') + i
).ToString());}}catch{strMsg
= "工作表" + sheetName
+ "中無數據";return null;}for (int i
= startIndex
; i
<= lastIndex
; i
++){IRow row
= sheet
.GetRow(i
);DataRow drNew
= dt
.NewRow();if (row
!= null){for (int j
= row
.FirstCellNum
; j
< row
.LastCellNum
; ++j
){if (row
.GetCell(j
) != null){ICell cell
= row
.GetCell(j
);switch (cell
.CellType
){case CellType
.Blank
:drNew
[j
] = "";break;case CellType
.Numeric
:short format
= cell
.CellStyle
.DataFormat
;if (format
== 14 || format
== 31 || format
== 57 || format
== 58)drNew
[j
] = cell
.DateCellValue
;elsedrNew
[j
] = cell
.NumericCellValue
;if (cell
.CellStyle
.DataFormat
== 177 || cell
.CellStyle
.DataFormat
== 178 || cell
.CellStyle
.DataFormat
== 188)drNew
[j
] = cell
.NumericCellValue
.ToString("#0.00");break;case CellType
.String
:drNew
[j
] = cell
.StringCellValue
;break;case CellType
.Formula
:try{drNew
[j
] = cell
.NumericCellValue
;if (cell
.CellStyle
.DataFormat
== 177 || cell
.CellStyle
.DataFormat
== 178 || cell
.CellStyle
.DataFormat
== 188)drNew
[j
] = cell
.NumericCellValue
.ToString("#0.00");}catch{try{drNew
[j
] = cell
.StringCellValue
;}catch { }}break;default:drNew
[j
] = cell
.StringCellValue
;break;}}}}dt
.Rows
.Add(drNew
);}return dt
;}public static string ExportToExcel(DataTable sourceTable
, string sheetName
= "result", string filePath
= null){if (sourceTable
.Rows
.Count
<= 0) return null;if (string.IsNullOrEmpty(filePath
)){filePath
= GetSaveFilePath();}if (string.IsNullOrEmpty(filePath
)) return null;bool isCompatible
= GetIsCompatible(filePath
);IWorkbook workbook
= CreateWorkbook(isCompatible
);ICellStyle cellStyle
= GetCellStyle(workbook
);ISheet sheet
= workbook
.CreateSheet(sheetName
);IRow headerRow
= sheet
.CreateRow(0);foreach (DataColumn column
in sourceTable
.Columns
){ICell headerCell
= headerRow
.CreateCell(column
.Ordinal
);headerCell
.SetCellValue(column
.ColumnName
);headerCell
.CellStyle
= cellStyle
;}int rowIndex
= 1;foreach (DataRow row
in sourceTable
.Rows
){IRow dataRow
= sheet
.CreateRow(rowIndex
);foreach (DataColumn column
in sourceTable
.Columns
){dataRow
.CreateCell(column
.Ordinal
).SetCellValue((row
[column
] ?? "").ToString());}rowIndex
++;}FileStream fs
= new FileStream(filePath
, FileMode
.OpenOrCreate
, FileAccess
.ReadWrite
);workbook
.Write(fs
);fs
.Dispose();sheet
= null;headerRow
= null;workbook
= null;return filePath
;}public static string ExportToExcel<T>(List
<T
> data
, IList
<KeyValuePair
<string, string>> headerNameList
, string sheetName
= "result", string filePath
= null) where T
: class{if (data
.Count
<= 0) return null;if (string.IsNullOrEmpty(filePath
)){filePath
= GetSaveFilePath();}if (string.IsNullOrEmpty(filePath
)) return null;bool isCompatible
= GetIsCompatible(filePath
);IWorkbook workbook
= CreateWorkbook(isCompatible
);ICellStyle cellStyle
= GetCellStyle(workbook
);ISheet sheet
= workbook
.CreateSheet(sheetName
);IRow headerRow
= sheet
.CreateRow(0);for (int i
= 0; i
< headerNameList
.Count
; i
++){ICell cell
= headerRow
.CreateCell(i
);cell
.SetCellValue(headerNameList
[i
].Value
);cell
.CellStyle
= cellStyle
;}Type t
= typeof(T
);int rowIndex
= 1;foreach (T item
in data
){IRow dataRow
= sheet
.CreateRow(rowIndex
);for (int n
= 0; n
< headerNameList
.Count
; n
++){object pValue
= t
.GetProperty(headerNameList
[n
].Key
).GetValue(item
, null);dataRow
.CreateCell(n
).SetCellValue((pValue
?? "").ToString());}rowIndex
++;}FileStream fs
= new FileStream(filePath
, FileMode
.OpenOrCreate
, FileAccess
.ReadWrite
);workbook
.Write(fs
);fs
.Dispose();sheet
= null;headerRow
= null;workbook
= null;return filePath
;}public static string ExportToExcel(DataGridView grid
, string sheetName
= "result", string filePath
= null){if (grid
.Rows
.Count
<= 0) return null;if (string.IsNullOrEmpty(filePath
)){filePath
= GetSaveFilePath();}if (string.IsNullOrEmpty(filePath
)) return null;bool isCompatible
= GetIsCompatible(filePath
);IWorkbook workbook
= CreateWorkbook(isCompatible
);ICellStyle cellStyle
= GetCellStyle(workbook
);ISheet sheet
= workbook
.CreateSheet(sheetName
);IRow headerRow
= sheet
.CreateRow(0);for (int i
= 0; i
< grid
.Columns
.Count
; i
++){ICell cell
= headerRow
.CreateCell(i
);cell
.SetCellValue(grid
.Columns
[i
].HeaderText
);cell
.CellStyle
= cellStyle
;}int rowIndex
= 1;foreach (DataGridViewRow row
in grid
.Rows
){IRow dataRow
= sheet
.CreateRow(rowIndex
);for (int n
= 0; n
< grid
.Columns
.Count
; n
++){dataRow
.CreateCell(n
).SetCellValue((row
.Cells
[n
].Value
?? "").ToString());}rowIndex
++;}AutoColumnWidth(sheet
, headerRow
.LastCellNum
- 1);FileStream fs
= new FileStream(filePath
, FileMode
.OpenOrCreate
, FileAccess
.ReadWrite
);workbook
.Write(fs
);fs
.Dispose();sheet
= null;headerRow
= null;workbook
= null;MessageBox
.Show("文件: " + filePath
+ ".xls 保存成功", "信息提示", MessageBoxButtons
.OK
, MessageBoxIcon
.Information
);return filePath
;}#endregionpublic static void AutoColumnWidth(ISheet sheet
, int cols
){for (int col
= 0; col
<= cols
; col
++){sheet
.AutoSizeColumn(col
);int columnWidth
= sheet
.GetColumnWidth(col
) / 256;for (int rowIndex
= 1; rowIndex
<= sheet
.LastRowNum
; rowIndex
++){IRow row
;if (sheet
.GetRow(rowIndex
) == null){row
= sheet
.CreateRow(rowIndex
);}else{row
= sheet
.GetRow(rowIndex
);}if (row
.GetCell(col
) != null){ICell cell
= row
.GetCell(col
);int contextLength
= Encoding
.UTF8
.GetBytes(cell
.ToString()).Length
;columnWidth
= columnWidth
< contextLength
? contextLength
: columnWidth
;}}sheet
.SetColumnWidth(col
, columnWidth
* 256);}}#region 公共導入方法public static DataTable ImportFromExcel(Stream excelFileStream
, string sheetName
, int headerRowIndex
, bool isCompatible
){IWorkbook workbook
= CreateWorkbook(isCompatible
, excelFileStream
);ISheet sheet
= null;int sheetIndex
= -1;if (int.TryParse(sheetName
, out sheetIndex
)){sheet
= workbook
.GetSheetAt(sheetIndex
);}else{sheet
= workbook
.GetSheet(sheetName
);}DataTable table
= GetDataTableFromSheet(sheet
, headerRowIndex
);excelFileStream
.Close();workbook
= null;sheet
= null;return table
;}public static DataTable ImportFromExcel(string excelFilePath
, string sheetName
, int headerRowIndex
){using (FileStream stream
= System
.IO
.File
.OpenRead(excelFilePath
)){bool isCompatible
= GetIsCompatible(excelFilePath
);return ImportFromExcel(stream
, sheetName
, headerRowIndex
, isCompatible
);}}public static DataSet ImportFromExcel(Stream excelFileStream
, int headerRowIndex
, bool isCompatible
){DataSet ds
= new DataSet();IWorkbook workbook
= CreateWorkbook(isCompatible
, excelFileStream
);for (int i
= 0; i
< workbook
.NumberOfSheets
; i
++){ISheet sheet
= workbook
.GetSheetAt(i
);DataTable table
= GetDataTableFromSheet(sheet
, headerRowIndex
);ds
.Tables
.Add(table
);}excelFileStream
.Close();workbook
= null;return ds
;}public static DataSet ImportFromExcel(string excelFilePath
, int headerRowIndex
){using (FileStream stream
= System
.IO
.File
.OpenRead(excelFilePath
)){bool isCompatible
= GetIsCompatible(excelFilePath
);return ImportFromExcel(stream
, headerRowIndex
, isCompatible
);}}#endregion#region 公共轉換方法public static string ConvertColumnIndexToColumnName(int index
){index
= index
+ 1;int system
= 26;char[] digArray
= new char[100];int i
= 0;while (index
> 0){int mod
= index
% system
;if (mod
== 0) mod
= system
;digArray
[i
++] = (char)(mod
- 1 + 'A');index
= (index
- 1) / 26;}StringBuilder sb
= new StringBuilder(i
);for (int j
= i
- 1; j
>= 0; j
--){sb
.Append(digArray
[j
]);}return sb
.ToString();}public static DateTime ConvertDate(object date
){string dtStr
= (date
?? "").ToString();DateTime dt
= new DateTime();if (DateTime
.TryParse(dtStr
, out dt
)){return dt
;}try{string spStr
= "";if (dtStr
.Contains("-")){spStr
= "-";}else if (dtStr
.Contains("/")){spStr
= "/";}string[] time
= dtStr
.Split(spStr
.ToCharArray());int year
= Convert
.ToInt32(time
[2]);int month
= Convert
.ToInt32(time
[0]);int day
= Convert
.ToInt32(time
[1]);string years
= Convert
.ToString(year
);string months
= Convert
.ToString(month
);string days
= Convert
.ToString(day
);if (months
.Length
== 4){dt
= Convert
.ToDateTime(date
);}else{string rq
= "";if (years
.Length
== 1){years
= "0" + years
;}if (months
.Length
== 1){months
= "0" + months
;}if (days
.Length
== 1){days
= "0" + days
;}rq
= "20" + years
+ "-" + months
+ "-" + days
;dt
= Convert
.ToDateTime(rq
);}}catch{throw new Exception("日期格式不正確,轉換日期失敗!");}return dt
;}public static decimal ConvertDecimal(object d
){string dStr
= (d
?? "").ToString();decimal result
= 0;if (decimal.TryParse(dStr
, out result
)){return result
;}else{throw new Exception("數字格式不正確,轉換數字失敗!");}}#endregion}
}
總結
以上是生活随笔為你收集整理的C# EXCEL的帮助类,仅使用NPOI,不用安装Office的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。