標籤:style blog http color 使用 os io strong
原文:C# 使用 NPOI 庫讀寫 Excel 檔案
NPOI 是開源的 POI 項目的.NET版,可以用來讀寫Excel,Word,PPT檔案。在處理Excel檔案上,NPOI 可以同時相容 xls 和 xlsx。官網提供了一份 Examples,給出了很多應用情境的例子,打包好的二進位檔案類庫,也僅有幾MB,使用非常方便。
讀Excel
NPOI 使用 HSSFWorkbook 類來處理 xls,XSSFWorkbook 類來處理 xlsx,它們都繼承介面 IWorkbook,因此可以通過 IWorkbook 來統一處理 xls 和 xlsx 格式的檔案。
以下是簡單的例子
public void ReadFromExcelFile(string filePath){ IWorkbook wk = null; string extension = System.IO.Path.GetExtension(filePath); try { FileStream fs = File.OpenRead(filePath); if (extension.Equals(".xls")) { //把xls檔案中的資料寫入wk中 wk = new HSSFWorkbook(fs); } else { //把xlsx檔案中的資料寫入wk中 wk = new XSSFWorkbook(fs); } fs.Close(); //讀取當前表資料 ISheet sheet = wk.GetSheetAt(0); IRow row = sheet.GetRow(0); //讀取當前行資料 //LastRowNum 是當前表的總行數-1(注意) int offset = 0; for (int i = 0; i <= sheet.LastRowNum; i++) { row = sheet.GetRow(i); //讀取當前行資料 if (row != null) { //LastCellNum 是當前行的總列數 for (int j = 0; j < row.LastCellNum; j++) { //讀取該行的第j列資料 string value = row.GetCell(j).ToString(); Console.Write(value.ToString() + " "); } Console.WriteLine("\n"); } } } catch (Exception e) { //只在Debug模式下才輸出 Console.WriteLine(e.Message); }}
Excel中的儲存格是有不同資料格式的,例如數字,日期,字串等,在讀取的時候可以根據格式的不同設定對象的不同類型,方便後期的資料處理。
//擷取cell的資料,並設定為對應的資料類型public object GetCellValue(ICell cell){ object value = null; try { if (cell.CellType != CellType.Blank) { switch (cell.CellType) { case CellType.Numeric: // Date comes here if (DateUtil.IsCellDateFormatted(cell)) { value = cell.DateCellValue; } else { // Numeric type value = cell.NumericCellValue; } break; case CellType.Boolean: // Boolean type value = cell.BooleanCellValue; break; case CellType.Formula: value = cell.CellFormula; break; default: // String type value = cell.StringCellValue; break; } } } catch (Exception) { value = ""; } return value;}
特別注意的是CellType中沒有Date,而日期類型的資料類型是Numeric,其實日期的資料在Excel中也是以數位形式儲存。可以使用DateUtil.IsCellDateFormatted方法來判斷是否是日期類型。
有了GetCellValue方法,寫資料到Excel中的時候就要有SetCellValue方法,缺的類型可以自己補。
//根據資料類型設定不同類型的cellpublic static void SetCellValue(ICell cell, object obj){ if (obj.GetType() == typeof(int)) { cell.SetCellValue((int)obj); } else if (obj.GetType() == typeof(double)) { cell.SetCellValue((double)obj); } else if (obj.GetType() == typeof(IRichTextString)) { cell.SetCellValue((IRichTextString)obj); } else if (obj.GetType() == typeof(string)) { cell.SetCellValue(obj.ToString()); } else if (obj.GetType() == typeof(DateTime)) { cell.SetCellValue((DateTime)obj); } else if (obj.GetType() == typeof(bool)) { cell.SetCellValue((bool)obj); } else { cell.SetCellValue(obj.ToString()); }}
cell.SetCellValue()方法只有四種重載方法,參數分別是string, bool, DateTime, double, IRichTextString
設定公式使用cell.SetCellFormula(string formula)
寫Excel
以下是簡單的例子,更多資訊可以參見官網提供的Examples。
public void WriteToExcel(string filePath){ //建立工作薄 IWorkbook wb; string extension = System.IO.Path.GetExtension(filePath); //根據指定的檔案格式建立對應的類 if (extension.Equals(".xls")) { wb = new HSSFWorkbook(); } else { wb = new XSSFWorkbook(); } ICellStyle style1 = wb.CreateCellStyle();//樣式 style1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;//文字水平對齊 style1.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//文字垂直對齊 //設定邊框 style1.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin; style1.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin; style1.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin; style1.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin; style1.WrapText = true;//自動換行 ICellStyle style2 = wb.CreateCellStyle();//樣式 IFont font1 = wb.CreateFont();//字型 font1.FontName = "楷體"; font1.Color = HSSFColor.Red.Index;//字型顏色 font1.Boldweight = (short)FontBoldWeight.Normal;//字型加粗樣式 style2.SetFont(font1);//樣式裡的字型設定具體的字型樣式 //設定背景色 style2.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index; style2.FillPattern = FillPattern.SolidForeground; style2.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index; style2.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;//文字水平對齊 style2.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//文字垂直對齊 ICellStyle dateStyle = wb.CreateCellStyle();//樣式 dateStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;//文字水平對齊 dateStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//文字垂直對齊 //設定資料顯示格式 IDataFormat dataFormatCustom = wb.CreateDataFormat(); dateStyle.DataFormat = dataFormatCustom.GetFormat("yyyy-MM-dd HH:mm:ss"); //建立一個表單 ISheet sheet = wb.CreateSheet("Sheet0"); //設定列寬 int[] columnWidth = { 10, 10, 20, 10 }; for (int i = 0; i < columnWidth.Length; i++) { //設定列寬度,256*字元數,因為單位是1/256個字元 sheet.SetColumnWidth(i, 256 * columnWidth[i]); } //測試資料 int rowCount = 3, columnCount = 4; object[,] data = { {"列0", "列1", "列2", "列3"}, {"", 400, 5.2, 6.01}, {"", true, "2014-07-02", DateTime.Now} //日期可以直接傳字串,NPOI會自動識別 //如果是DateTime類型,則要設定CellStyle.DataFormat,否則會顯示為數字 }; IRow row; ICell cell; for (int i = 0; i < rowCount; i++) { row = sheet.CreateRow(i);//建立第i行 for (int j = 0; j < columnCount; j++) { cell = row.CreateCell(j);//建立第j列 cell.CellStyle = j % 2 == 0 ? style1 : style2; //根據資料類型設定不同類型的cell object obj = data[i, j]; SetCellValue(cell, data[i, j]); //如果是日期,則設定日期顯示的格式 if (obj.GetType() == typeof(DateTime)) { cell.CellStyle = dateStyle; } //如果要根據內容自動調整列寬,需要先setCellValue再調用 //sheet.AutoSizeColumn(j); } } //合併儲存格,如果要合并的儲存格中都有資料,只會保留左上方的 //CellRangeAddress(0, 2, 0, 0),合并0-2行,0-0列的儲存格 CellRangeAddress region = new CellRangeAddress(0, 2, 0, 0); sheet.AddMergedRegion(region); try { FileStream fs = File.OpenWrite(filePath); wb.Write(fs);//向開啟的這個Excel檔案中寫入表單並儲存。 fs.Close(); } catch (Exception e) { Debug.WriteLine(e.Message); }}
如果想要設定儲存格為唯讀或可寫,可以參考這裡,方法如下:
ICellStyle unlocked = wb.CreateCellStyle();unlocked.IsLocked = false;//設定該儲存格為非鎖定cell.SetCellValue("未被鎖定");cell.CellStyle = unlocked;...//保護表單,password為解鎖密碼//cell.CellStyle.IsLocked = true;的儲存格將為唯讀sheet.ProtectSheet("password");
cell.CellStyle.IsLocked 預設就是true,因此sheet.ProtectSheet("password")一定要執行,才能實現鎖定儲存格,對於不想鎖定的儲存格,就一定要設定cell的CellStyle中的IsLocked = false