HSSFWorkbook:
是操作Excel2003以前(包括2003)的版本,扩展名是.xls;导出excel最常用的方式;但是此种方式的局限就是导出的行数至多为65535行,超出65536条后系统就会报错。
XSSFWorkbook:
是操作Excel2007后的版本,扩展名是.xlsx;为了突破HSSFWorkbook的65535行局限。其对应的是excel2007(1048576行,16384列)扩展名为“.xlsx”,最多可以导出104万行,不过这样就伴随着一个问题—OOM内存溢出,原因是你所创建的book sheet row cell等此时是存在内存的并没有持久化。
SXSSFWorkbook:
也是操作Excel2007后的版本,扩展名是.xlsx;SXSSFWorkbook是streaming版本的XSSFWorkbook,它只会保存最新的excel rows在内存里供查看,在此之前的excel rows都会被写入到硬盘里(Windows电脑的话,是写入到C盘根目录下的temp文件夹)。被写入到硬盘里的rows是不可见的/不可访问的。只有还保存在内存里的才可以被访问到。
所以会在默认的C盘目录下生成一些临时文件,默认路径是:
C:\Users\HAOHAO\AppData\Local\Temp\poifiles
最新版 SXSSFWorkbook代码示例 :
private void button4_Click(object sender, EventArgs e)
{
//创建SXSSFWorkbook对象
SXSSFWorkbook wb = new SXSSFWorkbook();
//创建sheet 并指定sheet的名字
ISheet sheet1 = wb.CreateSheet("详细数据");
//新建style对象并设置样式属性
ICellStyle style1 = wb.CreateCellStyle();//样式
IFont font1 = wb.CreateFont();//字体
font1.FontName = "宋体";
font1.FontHeightInPoints = 11;
font1.Boldweight = (short)FontBoldWeight.Bold;
style1.SetFont(font1);//样式里的字体设置具体的字体样式
//创建第一行
IRow row0 = sheet1.CreateRow(0);
//创建第一行第一列并设置值
row0.CreateCell(0).SetCellValue("姓名");
//获取第一行第一列并设置样式
row0.GetCell(0).CellStyle = style1;
row0.CreateCell(1).SetCellValue("年龄");
row0.GetCell(1).CellStyle = style1;
row0.CreateCell(2).SetCellValue("地址");
row0.GetCell(2).CellStyle = style1;
row0.CreateCell(3).SetCellValue("性别");
row0.GetCell(3).CellStyle = style1;
//构建大数据量
List<DataItem> bigData = new List<DataItem>();
for (int i = 0; i < 50000;i++ )
{
DataItem data = new DataItem();
data.Name = "霸道" + i;
data.Age = i;
data.Address = "青岛" + i;
data.Sex = i;
bigData.Add(data);
}
//循环添加数据
foreach (DataItem item in bigData)
{
int item_index = bigData.IndexOf(item);
//从第二行开始
IRow rowi = sheet1.CreateRow(item_index + 1);
rowi.CreateCell(0).SetCellValue(item.Name);
rowi.CreateCell(1).SetCellValue(item.Age);
rowi.CreateCell(2).SetCellValue(item.Address);
rowi.CreateCell(3).SetCellValue(item.Sex);
//设置列宽度,256*字符数,因为单位是1/256个字符
sheet1.SetColumnWidth(item_index, 256 * item.Address.Length * 4);
}
try
{
//将内存中的数据写入磁盘
using (FileStream filestream = new FileStream(System.IO.Path.Combine(@"D:\", "qizhi.xlsx"), FileMode.Create))
{
wb.Write(filestream);
filestream.Close();
}
}
catch (Exception ex)
{
Console.Write(ex);
}
MessageBox.Show("导出完成");
}