- public void ExportDataToExcel()
- {
- var workbook = new HSSFWorkbook();
- var sheet = workbook.CreateSheet("测试 NPOI");
- sheet.DefaultColumnWidth = 20;
- sheet.ForceFormulaRecalculation = true;
- var headFont = workbook.CreateFont();
- headFont.IsBold = true;
- // 标题列样式
- var headStyle = workbook.CreateCellStyle();
- headStyle.Alignment = HorizontalAlignment.Center;
- headStyle.BorderBottom = BorderStyle.Thin;
- headStyle.BorderLeft = BorderStyle.Thin;
- headStyle.BorderRight = BorderStyle.Thin;
- headStyle.BorderTop = BorderStyle.Thin;
- headStyle.SetFont(headFont);
- var rowIndex = 0;
- var row = sheet.CreateRow(rowIndex);
- var cell = row.CreateCell(0);
- cell.SetCellValue("姓名");
- cell.CellStyle = headStyle;
- cell = row.CreateCell(1);
- cell.SetCellValue("年龄");
- cell.CellStyle = headStyle;
- // 单元格边框
- var cellStyle=workbook.CreateCellStyle();
- cellStyle.BorderBottom = BorderStyle.Thin;
- cellStyle.BorderLeft = BorderStyle.Thin;
- cellStyle.BorderRight = BorderStyle.Thin;
- cellStyle.BorderTop = BorderStyle.Thin;
- for (var i = 1; i < 6; i++)
- {
- row = sheet.CreateRow(i);
- cell = row.CreateCell(0);
- cell.SetCellValue($"测试 {i}");
- cell.CellStyle = cellStyle;
- cell = row.CreateCell(1);
- cell.SetCellValue(i);
- cell.CellStyle = cellStyle;
- }
- // 公式计算
- row = sheet.CreateRow(7);
- cell = row.CreateCell(3);
- cell.SetCellValue(100);
- cell = row.CreateCell(4);
- cell.SetCellValue(200);
- cell = row.CreateCell(5);
- cell.CellFormula = "D8+E8";
string Path = @"D:\AA \ 导出 \";
- //Excel 的路径及名称
- string excelPath = Path + "AA1.xls";
- FileStream fileStream = new FileStream(excelPath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
- if (!workbook.IsWriteProtected)
- {
- workbook.Write(fileStream);
- }
- fileStream.Close();
- }
NuGet 安装 NPOI 版本 2.4.1
来源: http://www.bubuko.com/infodetail-2888740.html