62,046
社区成员
发帖
与我相关
我的任务
分享
public static bool ExportToExcel(DataTable table, string excelName, int[] columnIndexs, string[] columnHeads)
{
Excel.ApplicationClass oExcel = new Excel.ApplicationClass();
Excel.Workbook obook = null;
Excel.Worksheet oSheet = null;
Excel.Range range = null;
try
{
obook = oExcel.Workbooks.Add("");
oSheet = (Excel.Worksheet)obook.Worksheets[1];
int rCount, cCount;
rCount = table.Rows.Count;
cCount = table.Columns.Count;
object obj = System.Reflection.Missing.Value;
if (cCount < columnIndexs.Length || cCount < columnHeads.Length)
{
throw new ArgumentOutOfRangeException("columnIndexs 与 columnHeads 长度必须一致。");
}
for (int i = 1; i <= columnIndexs.Length; i++)
{
//Excel.Range = (Excel.Range)oSheet.Columns.get_Item(i, obj);
range = (Excel.Range)oSheet.Columns.get_Item(i, obj);
range.NumberFormatLocal = "@";
}
for (int c = 0; c < columnIndexs.Length; c++)
{
oSheet.Cells[1, c + 1] = columnHeads[c];
for (int r = 1; r <= rCount; r++)
{
oSheet.Cells[r + 1, c + 1] = table.Rows[r - 1][columnIndexs[c]].ToString();
}
}
obook.SaveCopyAs(excelName);
obook.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
return true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(obook);
oExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel);
GC.Collect();
}
}