概述
接上文NPOI大数据分批写入同个Excel,这次是利用task多任务同时写入到多个Excel。
Form2.cs
private void btnExport_Click(object sender, EventArgs e)
{
try
{
txtSql.SafeCall(() =>
{
txtSql.AppendText("开始处理...rn");
});
string sqlCount = Sql.GetRecordSql(GetBusinessType(), "");
recordCount = db.ExecuteScalar(sqlCount);
rowIndex = 0;
string[] sqlWhereArray = Sql.SqlWhereArray;
TaskFactory taskFactory = new TaskFactory();
Task[] tasks = new Task[sqlWhereArray.Length];
for (int k = 0; k < sqlWhereArray.Length; k++)
{
string sqlWhere = sqlWhereArray[k];
int sqlIndex = k;
tasks[sqlIndex] = new Task(Export, sqlIndex);
tasks[sqlIndex].Start();
}
taskFactory.ContinueWhenAll(tasks, TaskEnded, TaskContinuationOptions.None);
}
catch (Exception ex)
{
MessageBox.Show("发生异常,错误提示:" + ex.Message);
}
}
private void Export(object state)
{
BusinessType businessType = GetBusinessType();
string[] DateRemarkArray = Sql.DateRemarkArray;
string sql = "";
string sqlWhere = "";
int sqlIndex = (int)state;
DataTable dt = null;
lock (moniter)
{
sqlIndex = (int)state;
sqlWhere = Sql.SqlWhereArray[sqlIndex];
sql = Sql.GetDataSql(businessType, sqlWhere);
dt = db.GetDataSet(sql).Tables[0];
}
IWorkbook workbook = new XSSFWorkbook();
ISheet sheet = workbook.CreateSheet();
txtSql.SafeCall(() =>
{
txtSql.AppendText("条件" + (sqlIndex + 1).ToString() + ":" + DateRemarkArray[sqlIndex] + "rn");
});
IRow row0 = sheet.CreateRow(0);
for (int m = 0; m < dt.Columns.Count; m++)
{
DataColumn dc = dt.Columns[m];
row0.CreateCell(m).SetCellValue(dc.ColumnName);
}
for (int i = 0; i < dt.Rows.Count; i++)
{
System.Threading.Interlocked.Increment(ref rowIndex);
DataRow dr = dt.Rows[i];
IRow row = sheet.CreateRow(i+1);
for (int j = 0; j < dt.Columns.Count; j++)
{
row.CreateCell(j).SetCellValue(dr[j].ToString());
}
Label lbl = GetLabel(sqlIndex + 1);
lbl.SafeCall(() =>
{
if (i == (dt.Rows.Count - 1))
{
txtSql.AppendText("条件" + (sqlIndex + 1).ToString() + "完成,行数:" + (i + 1).ToString() + "rn");
lbl.Text = "条件" + (sqlIndex + 1).ToString() + "完成";
}
else
{
lbl.Text = string.Format("正在导出第{0}个条件,第{1}行", (sqlIndex + 1).ToString(), (i + 1).ToString());
}
double x = rowIndex * 1.0 / recordCount * 100;
lblProgress.Text = string.Format("总行数:{0}, 当前完成总{1}行,百分占比:{2} %", recordCount.ToString(), rowIndex.ToString(), x.ToString("#0.0"));
});
}
string fileName = string.Format("{0}_{1}.xlsx", businessType.ToString(), DateRemarkArray[sqlIndex]);
FileStream outFs = new FileStream(fileName, FileMode.Create);
workbook.Write(outFs);
outFs.Close();
}
最后
以上就是含蓄黑米为你收集整理的NPOI利用多任务模式分批写入多个Excel的全部内容,希望文章能够帮你解决NPOI利用多任务模式分批写入多个Excel所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复