dimanche 19 avril 2015

Export datagridview to word document c#

I'm trying to export data grid to word document. But instead of this result:



EmployeeID EmployeeName Birth Phone Address DateOfHiring Salary EmloyeeType
1 name 1 11 test 1.1.1111 1 testTy
2 name2 2 22 test 2.2.2222 2 test2Ty


I'm getting something like this:



EmployeeID EmpoyeeName Birth Phone Address DateOfHiring Salary
EmployeeType
1 name 1.1.1111

2 name2 2.2.2222


All record are mixed. How to save datagrid in the format that it originally was? Here is the code that I use to perform export:



private void ReportButton_Click(object sender, EventArgs e)
{
string filename = @"D:\...\AllEmployees.doc";
ToCsV(dataGridView1, filename);
}
private void ToCsV(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 utf8 = Encoding.UTF8;
byte[] output = utf8.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();


}

Aucun commentaire:

Enregistrer un commentaire