![](/img/trans.png)
[英]How to add a new excel column between two columns in a existing worksheet
[英]How to add excel column to worksheet
有誰知道如何在現有工作表中插入新列。
我現在的當前解決方案是通過復制現有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);
}
}
打開現有的excel工作表,並使用如下所述的使用Range的工作表獲取columncount和Rowcount,並將此值轉換為rangeaddress以寫入現有的excel工作表
Sheet.UsedRange.Columns.Count
Sheet.UsedRagne.Rows.Count
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.