文章有點水,和前幾篇沒有太大區別,但是單線程處理大文件導出會非常耗時間,用到多線程才能更加合理的利用資源。大文件也可能會超出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();//強行銷毀
}