收集了两种方法,一种是直接利用I/o读写去生成非标准格式的xls文件,速度很快。另外种就是直接使用EXCEL的COM组件实现,需要在项目中引用EXCEL的COM组件。
IO方法:
public void exportFromDataTable(System.Data.DataTable dt, string pathName)
{
FileStream objFileStream;
StreamWriter objStreamWriter;
string strLine = " ";
objFileStream = new FileStream(pathName, FileMode.OpenOrCreate, FileAccess.Write);
objStreamWriter = new StreamWriter(objFileStream, System.Text.Encoding.Unicode);
//循环写入列头名称
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 = 1; j < dt.Columns.Count; j++)
{
strLine = strLine + dt.Rows[i][j].ToString() + Convert.ToChar(9);
}
objStreamWriter.WriteLine(strLine);
strLine = " ";
}
objStreamWriter.Close();
objFileStream.Close();
}
COM组件方法:
public void ExportToExcelByExcel(System.Data.DataTable dt, string pathName)
{
object objOpt = System.Reflection.Missing.Value;
Excel.Application excel = new Excel.Application();
excel.Visible = true;
Workbook wkb = excel.Workbooks.Add(objOpt);
Worksheet wks = (Worksheet)wkb.ActiveSheet;
wks.Visible = XlSheetVisibility.xlSheetVisible;
int rowIndex = 1;
int colIndex = 0;
System.Data.DataTable table = dt;
foreach (DataColumn col in table.Columns)
{
colIndex++;
excel.Cells[1, colIndex] = col.ColumnName;
}
foreach (DataRow row in table.Rows)
{
rowIndex++;
colIndex = 0;
foreach (DataColumn col in table.Columns)
{
colIndex++;
excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
}
}
try
{
wkb.SaveAs(pathName, objOpt, null, null, false, false, XlSaveAsAccessMode.xlNoChange, ConflictOption.OverwriteChanges, null, null, null, null);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
wkb.Close(false, objOpt, objOpt);
excel.Quit();
}
}
引用3个DLL:Interop.Excel.dll,Interop.VBIDE.dll,Interop.Office.dll(下载地址见下)
在项目中:using Excel;
调用示例方法如下:
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
ExportToExcel excel = new ExportToExcel();
excel.exportFromDataTable((DataTable)dataGridViewX1.DataSource, saveFileDialog1.FileName);
MessageBox.Show("成功");
}