Can you say me, how can i save the contents of DataGridView to Exel File with the Formatting cells Backcolor/Forecolor? I have DGV like this:
And when I try to Export Data to Excel I get the data, but without Forecolor, I have tried a several of ways, but it does not work! Beforehand Thank you!
private void btnExport_Click(object sender, EventArgs e) {
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel Documents (*.xls)|*.xls";
sfd.FileName = "export.xls";
if (sfd.ShowDialog() == DialogResult.OK)
{
//ToCsV(dataGridView1, @"c:\export.xls");
ToCsV1(dataGridView1, sfd.FileName);
}
}
private void ToCsV1(DataGridView dGV, string filename) { string stOutput = ""; // Export titles: string sHeaders = "";
for (int j = 0; j < dGV.Columns.Count; j++)
sHeaders = sHeaders.ToString() + Convert.ToString(dGV.Columns[j].HeaderText) + "\t";
stOutput += sHeaders + "\r\n";
// Export data.
for (int i = 0; i < dGV.RowCount - 1; i++)
{
string stLine = "";
for (int j = 0; j < dGV.Rows[i].Cells.Count; j++)
stLine = stLine.ToString() + Convert.ToString(dGV.Rows[i].Cells[j].Value) + "\t";
stOutput += stLine + "\r\n";
}
Encoding utf16 = Encoding.GetEncoding(1254);
byte[] output = utf16.GetBytes(stOutput);
FileStream fs = new FileStream(filename, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(output, 0, output.Length); //write the encoded file
bw.Flush();
bw.Close();
fs.Close();
}