【发布时间】:2017-03-14 18:49:59
【问题描述】:
有谁知道如何在现有工作表中插入新列。
我目前的解决方案是通过复制现有 excel 中的所有列来创建一个新的 excel 文件,然后在数据表中添加新的 col,然后将其导出以创建一个新的 excel。这种方法有点乏味,只是将新列添加到已经存在的 excel 中是我看到的最好的方法。
这是我创建新 excel 文件的函数
public static void ExportToExcel(DataTable tbl)
{
try
{
string dateNow = String.Format("{0:MM_dd_yyyy HH_mm_ss}", DateTime.Now);
string excelFilePath = "C:\\The_Excel_File\\Result_" + dateNow;
if (tbl == null || tbl.Columns.Count == 0)
throw new Exception("ExportToExcel: Null or empty input table!\n");
// load excel, and create a new workbook
var excelApp = new Microsoft.Office.Interop.Excel.Application();
excelApp.Workbooks.Add();
// single worksheet
Microsoft.Office.Interop.Excel._Worksheet workSheet = excelApp.ActiveSheet;
// column headings
for (var i = 0; i < tbl.Columns.Count; i++)
{
workSheet.Cells[1, i + 1] = tbl.Columns[i].ColumnName;
}
// rows
for (var i = 0; i < tbl.Rows.Count; i++)
{
// to do: format datetime values before printing
for (var j = 0; j < tbl.Columns.Count; j++)
{
workSheet.Cells[i + 2, j + 1] = tbl.Rows[i][j];
}
}
// check file path
if (!string.IsNullOrEmpty(excelFilePath))
{
try
{
workSheet.SaveAs(excelFilePath);
excelApp.Quit();
//MessageBox.Show("Excel file saved!");
}
catch (Exception ex)
{
throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
+ ex.Message);
}
}
else
{ // no file path is given
excelApp.Visible = true;
}
}
catch (Exception ex)
{
throw new Exception("ExportToExcel: \n" + ex.Message);
}
}
【问题讨论】: