多线程导出大规模excel文件
文章有点水,和前几篇没有太大区别,但是单线程处理大文件导出会非常耗时间,用到多线程才能更加合理的利用资源。大文件也可能会超出excel工作表范围。这里也有相应处理
参考:用DataGridView导入TXT文件,并导出为XLS文件
参考:c#多线程介绍(上)
private void button1_Click(object sender, EventArgs e)
{
string fileName = "";
openFileDialog1.Multiselect = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string[] filePath = openFileDialog1.FileNames;
foreach (string name in filePath)
{
fileName = name;
Thread thread = new Thread(new ParameterizedThreadStart(Go));
thread.Start(fileName );
}
}
}
private void Go(object fileName1)
{
string fileName = (string)fileName1;
System.Data.DataTable dt = new System.Data.DataTable();
StreamReader sr = new StreamReader(fileName, Encoding.UTF8);
for (int i = 0; i < 9; i++)
{
dt.Columns.Add(i.ToString());
}
while (true)
{
string strLine = sr.ReadLine();
if (string.IsNullOrEmpty(strLine) == true)
{
break;
}
else
{
DataRow dr = dt.NewRow();
string[] strList = strLine.Split('|');
int j = 0;
for (int i = 0; i < strList.Length - 1; i++)
{
dr[j.ToString()] = strList[i];
j++;
if (j == 9)
{
j = 0;
dt.Rows.Add(dr);
}
}
}
}
sr.Close();
OutPutAsExcelFile(dt,fileName);
}
private void OutPutAsExcelFile(System.Data.DataTable dt,string fileName)
{
fileName += ".xls";
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
MessageBox.Show("无法创建Excel对象,您的电脑可能未安装Excel");
return;
}
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
MessageBox.Show(dt.Rows.Count.ToString());
int n = dt.Rows.Count / (2 << 15) + 1;
MessageBox.Show(n.ToString());
if (n > 3)
{
for (int i = 0; i < n - 3; i++)
{
xlApp.Sheets.Add();
}
}
for (int i = 1; i <= n; i++)
{
((Microsoft.Office.Interop.Excel.Worksheet)xlApp.Sheets[i]).Name = i.ToString();//修改SHEET名
}
for (int l = 0; l < n; l++)
{
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[l + 1];//取得sheet
//Microsoft.Office.Interop.Excel.Worksheet worksheet2 = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[2];//取得sheet2
int CurrentRow = l * 65536;
for (int r = 0; r < 65536; r++)
{
if (r + CurrentRow == dt.Rows.Count)
break;
for (int i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[r + 1, i + 1] = dt.Rows[r + CurrentRow][i];
}
System.Windows.Forms.Application.DoEvents();
}
worksheet.Columns.EntireColumn.AutoFit();//列宽自适
}
MessageBox.Show(fileName + "的简明资料保存成功", "提示", MessageBoxButtons.OK);
if (fileName != "")
{
try
{
workbook.Saved = true;
workbook.SaveCopyAs(fileName);
//fileSaved = true;
}
catch (Exception ex)
{
//fileSaved = false;
MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
}
}
xlApp.Quit();
GC.Collect();//强行销毁
}