excel导出,最好将需导出的内容与DataTable绑定。可参照~
public static bool FastExportToExcel(System.Data.DataTable dt, ProgressBar proBar, System.Windows.Forms.Label labPercent)
{
System.Windows.Forms.SaveFileDialog saveDia = new SaveFileDialog();
saveDia.Filter = "Excel|*.xls";
saveDia.Title = "导出为Excel文件";
if (!(saveDia.ShowDialog() == System.Windows.Forms.DialogResult.OK
&& !string.Empty.Equals(saveDia.FileName)))
{
return false;
}
long totalCount = dt.Rows.Count;
long rowRead = 0;
float percent = 0;
string FileName = "";
FileName = saveDia.FileName;
FileStream objFileStream;
StreamWriter objStreamWriter;
string strLine = "title";
objFileStream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write);
objStreamWriter = new StreamWriter(objFileStream, Encoding.Unicode);
//objStreamWriter.WriteLine(strLine);//寫入標題
strLine = "";
for (int i = 0; i < dt.Columns.Count; i++)
{
strLine = strLine + dt.Columns[i].ColumnName.ToString() + "" + Convert.ToChar(9);
}
objStreamWriter.WriteLine(strLine);
strLine = "";
for (int i = 0; i < dt.Rows.Count; i++)
{
//strLine = strLine + (i + 1) + Convert.ToChar(9);//增加序號
for (int j = 0; j < dt.Columns.Count; j++)
{
if (dt.Columns[j].ColumnName.ToLower() == "time" && dt.Rows[i][j] != Convert.DBNull)
{
string strDateTime = Convert.ToDateTime(dt.Rows[i][j]).ToString("yyyy/MM/dd HH:mm:ss.fff");
strLine = strLine + " " + strDateTime + Convert.ToChar(9); //9:tab字符
}
else
{
strLine = strLine + dt.Rows[i][j].ToString() + Convert.ToChar(9); //9:tab字符
}
}
objStreamWriter.WriteLine(strLine);
strLine = "";
rowRead++;
percent = ((float)(100 * rowRead)) / totalCount;
System.Windows.Forms.Application.DoEvents();
labPercent.Text = percent + "%"; labPercent.Refresh();//顯示百分比進度
proBar.Value += 1;
}
objStreamWriter.Close();
objFileStream.Close();
return true;
}