I could export data of datagridview to excel. But the actual format of datagridview was not exported i.e., font, color and space. So, is there any best way to export datagridview to excel i.e. not only data but also the look.
The sample look is this:
Right click on your project and select Add Reference menu. After that go to COM tab and select and add Microsoft Excel 12.0 object library. Now here is my Button click event handler where I create Excel object and document, get data from DataGridView and add rows and columns to the document.
Add a link button in the View and name it DownloadExcel. Now, create a Method in Controller and add the following code to Export the data in Excel. Now, run the project and click on the "Download Excel" button. The data is downloaded in Excel format.
Try CSV export
private void ToCsV(DataGridView dGV, string filename)
{
string separator = ",";
StringBuilder stOutput = new StringBuilder();
// Export titles:
StringBuilder sHeaders = new StringBuilder();
for (int j = 0; j < dGV.Columns.Count; j++)
{
sHeaders.Append(dGV.Columns[j].HeaderText);
sHeaders.Append(separator);
}
stOutput.AppendLine(sHeaders.ToString());
// Export data.
for (int i = 0; i < dGV.RowCount - 1; i++)
{
StringBuilder stLine = new StringBuilder();
for (int j = 0; j < dGV.ColumnCount; j++)
{
stLine.Append(Convert.ToString(dGV[j, i].Value));
stLine.Append(separator);
}
stOutput.AppendLine(stLine.ToString());
}
File.WriteAllText(filename, stOutput.ToString());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With