NickMalloy
asked on
.net command application export data to excel
I'm trying to export data to excel from a datatable. currently all the data goes into column one and I can't figure out why. Can someone help?
public static void ExportToExcel(System.Data.DataTable dt, string excelFilePath = null)
{
// string FileName = "Test.xls";
string fullpath = excelFilePath;
int tblborder = 2;
StreamWriter SW;
SW = File.CreateText(fullpath);
StringBuilder objSB = new StringBuilder();
objSB.Append("<Table border=" + tblborder + " width=100%>");
objSB.Append("<tr>");
for (int i = 0; i < dt.Columns.Count; i++)
{
objSB.Append("<th valign=middle>" + dt.Columns[i].ColumnName + "</th>");
}
objSB.Append("</tr>");
objSB.Append("<tr>");
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
objSB.Append("<tr>");
objSB.Append("<td align=center>" + dt.Rows[i][j].ToString() + "</td>");
objSB.Append("</tr>");
}
}
objSB.Append("</Table>");
SW.Write(objSB.ToString());
SW.Close();
// Response.Redirect(filePath);
}
Both of those are looping over the columns defined in your datatable. So, what is the structure of your datatable? You can drop a breakpoint and inspect the content / structure of the datatable in debug.
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
The 2nd code works for me though I do have a problem opening the file after but I think that's because of the filename/format I used when testing.
Have you tried stepping through the code? Perhaps even with Excel visible to see what's actually happening there.
Have you tried stepping through the code? Perhaps even with Excel visible to see what's actually happening there.
ASKER
Thanks for the help
ASKER
Open in new window