之前轉過一篇類似的文章,那個是用C#自帶的excel類操作Excel的,還有一種在c#上操作excel的方法便是npoi了,npoi是poi的C#版本。
npoi操作excel有兩種形式,一種是hssf和xssf。hssf是用來生成excel2003之前的版本,生成的excel后綴是“.xls”,而xssf是excel2007的版本,操作的excel的后綴是“.xlsx”。
npoi中常用的類型:
XSSF/HSSFWorkbook:excel文件的工作簿,
Isheet:excel文件的工作簿中的工作表,
IRow:excel文件的工作簿中的工作表中的行,
ICell:excel文件的工作簿中的工作表中的行中的單元格。
舉一個簡單的導出excel的方法
public static IWorkbook TableToExcel(DataTable dt, string fileExt = ".xlsx") { IWorkbook workbook; if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(); } else { workbook = null; } if (workbook == null) { return null; } ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName); //表頭 IRow row = sheet.CreateRow(0); for (int i = 0; i < dt.Columns.Count; i++) { ICell cell = row.CreateCell(i); cell.SetCellValue(dt.Columns[i].ColumnName); } //數據 for (int i = 0; i < dt.Rows.Count; i++) { IRow row1 = sheet.CreateRow(i + 1); for (int j = 0; j < dt.Columns.Count; j++) { ICell cell = row1.CreateCell(j); cell.SetCellValue(dt.Rows[i][j].ToString()); } } //設置寬度 for (int i = 0; i < dt.Columns.Count; i++) { int length = Encoding.Default.GetBytes(row.GetCell(i).ToString()).Length; sheet.SetColumnWidth(i, (length + 2) * 256); } return workbook; }
//生成excel:
using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
var buffer = ms.GetBuffer();
ms.Close();
return File(buffer, "application/vnd.ms-excel", "個人提成補錄模板.xls");
}
如果要更改單元格顏色的樣式,可以用下面的方法:
ICellStyle style = workbook.CreateCellStyle(); style.FillPattern = FillPattern.SolidForeground;//很重要 style.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.Red.Index; style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Red.Index; IRow excelRow = workbook.GetSheetAt(0).GetRow(0); for (int i = 0; i <= 5; i++) { excelRow.GetCell(i).CellStyle = style; } excelRow.GetCell(22).CellStyle = style; excelRow.GetCell(19).CellStyle = style; excelRow.GetCell(8).CellStyle = style;
改顏色糾結了好久,也查了好多資料,網上有好多用cell.setcellstyle()這個方法的,我試了一下,根本沒有,而且好多都是那樣寫的,不知道是java的還是啥的,應該不是.net的。
