I have a datatable that I created programmatically (no connection used etc) and in my datatable I have 2 columns. I would only like to export the value from 2nd column to excel. For my code below, it export the data from both columns inside excel. How do I write for exporting only a specific column?
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();
}
Copy your DataTable
into temporary table and remove columns, you don't want and then export to excel.
Example:
DataTable tempDataTable;
tempDataTable = table.Copy();
tempDataTable.Columns.Remove("NameOfColumnYouDontWant");
In your code:
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();
}