NPOI生成EXCEL
#region 生成Excel表格
public static string wenjianname = "";
//生成
public void ToExcel()
{
try
{
string strpath = ""; string serverPath = "";
if (System.IO.Directory.Exists(serverPath) == false)
{
System.IO.Directory.CreateDirectory(serverPath);
}
//System.IO.Directory.GetCurrentDirectory() //程序所在路径
string path1 = System.IO.Directory.GetCurrentDirectory() + @"\ceshi\";
string name = "报告" + "_" + DateTime.Now.ToString("yyyyMMddhhmmss");
wenjianname = name;
string fileName = Path.GetDirectoryName(path1) + name; //D:\ftp
FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate);
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
ISheet sheet = hssfworkbook.CreateSheet("ceshi2"); //创建sheet页
ISheet sheet1 = hssfworkbook.GetSheet("ceshi2"); //获取sheet页
IFont font = hssfworkbook.CreateFont();
font.FontName = "宋体";
font.FontHeightInPoints = 12;
ICellStyle cellStyle = hssfworkbook.CreateCellStyle();
cellStyle.SetFont(font);
cellStyle.Alignment = HorizontalAlignment.Left;
cellStyle.VerticalAlignment = VerticalAlignment.Center;
cellStyle.BorderBottom = BorderStyle.Thin;
cellStyle.BorderLeft = BorderStyle.Thin;
cellStyle.BorderRight = BorderStyle.Thin;
cellStyle.Alignment = HorizontalAlignment.Left;
var dic = new Dictionary<int, int>();
ICell[] cell = CreateCells(sheet1, cellStyle, 0, 10); // 创建第一行,十列
cell[0].SetCellValue("电芯ID"); //赋值
cell[1].SetCellValue("库位");
cell[2].SetCellValue("温度传感");
cell[3].SetCellValue("开始时间");
cell[4].SetCellValue("结束时间");
cell[5].SetCellValue("库位开始温度℃");
cell[6].SetCellValue("库位结束温度℃");
cell[7].SetCellValue("库位最高温度℃");
cell[8].SetCellValue("库位最低温度℃");
cell[9].SetCellValue("库位平均温度℃");
for (int i = 0; i < 4; i++)
{
ICell[] cells = CreateCells(sheet, cellStyle, i + 1, 10);
for (int j = 0; j < 10; j++)
{
cells[j].SetCellValue(i + 1);//赋值
}
}
string files = string.Format("{0}.xls", name, System.Text.Encoding.UTF8);
FileStream file = new FileStream(Path.Combine(serverPath, files), FileMode.Create);
hssfworkbook.Write(file);
//hssfworkbook.Dispose();
fs.Close();file.Close(); //关闭进程
MessageBox.Show("生成成功");
//file.Dispose();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
//单元格样式
private static ICell[] CreateCells(ISheet sheet, ICellStyle cellStyle, int addRowIndex, int cellcount)
{
ICell[] cells = new ICell[cellcount];
IRow row = sheet.CreateRow(addRowIndex);
row.HeightInPoints = 24.95f;
for (int i = 0; i < cellcount; i++)
{
cells[i] = row.CreateCell(i);
cells[i].CellStyle = cellStyle;
}
return cells;
}
#endregion