C# 使用NPOI,导出excel文件
/// <summary>
/// 导出excel文件
/// </summary>
/// <param name="dt">Table表数据</param>
/// <param name="path">存放路径 ( string path = System.Environment.CurrentDirectory + "\\";)</param>
public void exportWPS_excel(DataTable dt, string path)
{
//创建excel工作薄
IWorkbook wb = new HSSFWorkbook();
//创建excel单元格样式
ICellStyle cellStyle = wb.CreateCellStyle();
//水平对齐
cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
//垂直对齐
cellStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
IFont font = wb.CreateFont();
//创建表
IDataFormat format = wb.CreateDataFormat();
ISheet sh = wb.CreateSheet("Table");
var newrow = sh.CreateRow(0); //第一行
newrow.CreateCell(0);
newrow.Cells[0].SetCellValue("2021年");//表头标题
ICellStyle headStyle0 = wb.CreateCellStyle();
headStyle0.WrapText = true;
IFont fontt = wb.CreateFont();
fontt.FontHeightInPoints = 12; //字体大小
fontt.Boldweight = short.MaxValue;//设置字体加粗样式
headStyle0.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
headStyle0.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
headStyle0.SetFont(fontt);
newrow.GetCell(0).CellStyle = headStyle0;
int count = dt.Columns.Count - 2;
sh.AddMergedRegion(new CellRangeAddress(0, 0, 0, dt.Columns.Count - 1));//合并单元格(起始行,终止行,起始列,终止列)
#region 表头及样式
int cellIndex = 0;
IRow headerRow = sh.CreateRow(1);//第二行
for (int i = 0; i < dt.Columns.Count; i++)
{
//设置行高
headerRow.HeightInPoints = 25;
headerRow.CreateCell(cellIndex).SetCellValue(tablename(dt.Columns[i].ColumnName));
ICellStyle headStyle = wb.CreateCellStyle();
sh.AutoSizeColumn(cellIndex);//自适应宽度
headStyle.WrapText = true;
font.FontHeightInPoints = 12; //字体大小
font.Boldweight = short.MaxValue;//设置字体加粗样式
headStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
headStyle.SetFont(font);
headerRow.GetCell(cellIndex).CellStyle = headStyle;
cellIndex++;
}
#endregion
#region 数据填充
int rowIndex = 2;//行数一定要从2行开始,因为上面已经创建了标题为0行,数据表头为1行;
foreach (DataRow row in dt.Rows)
{
int ColumnIndex = 0;
IRow dataRow = sh.CreateRow(rowIndex);
foreach (DataColumn column in dt.Columns)
{
ICell newCel0 = dataRow.CreateCell(ColumnIndex);//序号
dataRow.GetCell(ColumnIndex).CellStyle = cellStyle;
cellStyle.DataFormat = format.GetFormat("text");//数据类型
newCel0.SetCellValue(row[column.ColumnName].ToString());
sh.AutoSizeColumn(ColumnIndex);//自适应宽度
ColumnIndex++;
}
rowIndex++;
}
#endregion
int rows = dt.Rows.Count + 2;//获取dt行数
var newroww = sh.CreateRow(rows); //添加总结行
newroww.CreateCell(0);
newroww.Cells[0].SetCellValue("共" + dt.Rows.Count + "个标本");
//设置新建文件路径及名称
string savePath = path + "导出Excel\\" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".xls";
using (FileStream fileStream = File.OpenWrite(savePath))
{
wb.Write(fileStream);
MessageBox.Show("提示:创建成功!");
}
}
最终导出后如图


浙公网安备 33010602011771号