如何从数据表中的特定列加载数据
How to load data from a specific column in datatable
我有一个以编程方式创建的数据表(未使用连接等),在我的数据表中有 2 列。我只想将第 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();
}
将您的 DataTable
复制到临时 table 并删除您不需要的列,然后导出到 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();
}
我有一个以编程方式创建的数据表(未使用连接等),在我的数据表中有 2 列。我只想将第 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();
}
将您的 DataTable
复制到临时 table 并删除您不需要的列,然后导出到 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();
}