NPOI大数据分批写入同个Excel
实现过程:
要导出来的数据库数据量很大,一次取出来压力有点大,故分批取出来,导入到同一个Excel。
因为Excel2003版最大行数是65536行,Excel2007开始的版本最大行数是1048576行,故NPOI导出时候选择了Excel2007。
Form1.cs
[csharp] view plaincopyprint?
/*
引用命名空间:
using System.IO;
using System.Threading.Tasks;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
*/
public Form1()
{
InitializeComponent();
List<DictionaryEntry> list = new List<DictionaryEntry>(){
new DictionaryEntry(1, "XA"),
new DictionaryEntry(2, "XB")
};
cbType.BindComboBox(list);
}
private void CreateExcel(string fileName)
{
if (File.Exists(fileName))
File.Delete(fileName);
IWorkbook workbook = new XSSFWorkbook();
ISheet sheet = workbook.CreateSheet("Sheet1");
FileStream sw = File.Create(fileName);
workbook.Write(sw);
sw.Close();
}
private void btnExport_Click(object sender, EventArgs e)
{
try
{
Task.Factory.StartNew(() =>
{
txtSql.SafeCall(() =>
{
txtSql.AppendText("开始处理...\r\n");
});
BusinessType businessType = GetBusinessType();
string[] sqlWhereArray = Sql.SqlWhereArray;
string[] DateRemarkArray = Sql.DateRemarkArray;
string fileName = string.Format("{0}.xlsx", businessType.ToString());
CreateExcel(fileName);
string sqlCount = Sql.GetRecordSql(businessType, "");
int recordCount = db.ExecuteScalar(sqlCount);
int sqlIndex = 0;
int rowIndex = 0;
foreach (string sqlWhre in sqlWhereArray)
{
sqlIndex++;
FileStream fs = File.Open(fileName, FileMode.Open);
IWorkbook workbook = new XSSFWorkbook(fs);
ISheet sheet = workbook.GetSheetAt(0);
txtSql.SafeCall(() =>
{
txtSql.AppendText("条件" + sqlIndex.ToString() + ":" + DateRemarkArray[sqlIndex - 1]);
});
string sql = Sql.GetDataSql(businessType, sqlWhre);
DataTable dt = db.GetDataSet(sql).Tables[0];
int columnsCount = dt.Columns.Count;
if (sqlIndex == 1)
{
IRow row0 = sheet.CreateRow(0);
for (int m = 0; m < columnsCount; m++)
{
DataColumn dc = dt.Columns[m];
row0.CreateCell(m).SetCellValue(dc.ColumnName);
}
}
for (int i = 0; i < dt.Rows.Count; i++)
{
rowIndex++;
&nb
补充:软件开发 , C++ ,