我有一个以编程方式创建的数据表(未使用连接等),在我的数据表中有2列。我只想将值从第二列导出到excel。对于下面的代码,它从excel中的两列导出数据。如何编写仅导出特定列的内容?
private void button2_Click(object sender, EventArgs e)
{
using (ExcelPackage pck = new ExcelPackage())
{
string filepath = "C:\\Trial.xlsx";
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("test");
ws.Cells["A1"].LoadFromDataTable(dt1, false);
pck.SaveAs(new FileInfo(filepath));
}
this.Close();
}
答案 0 :(得分:1)
将DataTable
复制到临时表中并删除不需要的列,然后导出到excel。
示例:
DataTable tempDataTable;
tempDataTable = table.Copy();
tempDataTable.Columns.Remove("NameOfColumnYouDontWant");
在您的代码中:
private void button2_Click(object sender, EventArgs e)
{
using (ExcelPackage pck = new ExcelPackage())
{
string filepath = "C:\\Trial.xlsx";
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("test");
DataTable tempDataTable;
tempDataTable = dt1.Copy();
tempDataTable.Columns.Remove("NameOfColumnYouDontWant");
# Remove all columns you don't need
ws.Cells["A1"].LoadFromDataTable(tempDataTable, false);
pck.SaveAs(new FileInfo(filepath));
}
this.Close();
}