将数据从gridview导出到word文件时,应该在word中创建一个表,
表可能包含许多单元格,
在每个单元格中,我需要存储从gridview
导出的一条记录I have exported the data from gridview to word,
like this
1 rasdf sdf
2 sdf jlkj
3 dfdf dfdf
4 dsaf sdfdsfds
5 king mumbai
but i need the output in table format in which Each record should be in one cell, second cell contains another records
![OUTput view is attached with this link][1]
这是我编写的代码
private void button5_Click(object sender, EventArgs e)
{
// Table table = new table();
sfd.Filter = "Excel Documents (*.doc)|*.doc";
if (sfd.ShowDialog() == DialogResult.OK)
{
ExportToWord();
}
}
private void ExportToWord()
{
string strForPrint = "";
//writing bill fields
// strForPrint += "Bill No : " + txtBillNo.Text + "\t";
//strForPrint += "Date : " + dtpDate.Text + "\r\n\r\n";
//strForPrint += "Customer Name : " + txtCustomer.Text + "\r\n\r\n";
//strForPrint += "Remarks : " + txtRemarks.Text + "\r\n\r\n\r\n";
strForPrint += "-----Bill Detail-----" + "\r\n\r\n\r\n";
// writing datagridview column titles:
string strHeaderTitle = "";
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
strHeaderTitle = strHeaderTitle.ToString() + Convert.ToString(dataGridView1.Columns[j].HeaderText) + "\t\t";
}
//strForPrint += strHeaderTitle + "\r\n";
// writing datagridview data.
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
string strLineData = "";
for (int j = 0; j < dataGridView1.Rows[i].Cells.Count; j++)
{
strLineData = strLineData.ToString() + Convert.ToString(dataGridView1.Rows[i].Cells[j].Value);
if (j == 1)
{
strLineData = strLineData + "\t\t\t";
}
else
{
strLineData = strLineData + "\t\t";
}
}
strForPrint += strLineData + "\r\n";
}
Encoding utf16 = Encoding.GetEncoding(1254);
byte[] output = utf16.GetBytes(strForPrint);
FileStream fs = new FileStream(sfd.FileName, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(output, 0, output.Length); //write data into file
MessageBox.Show("File Created.....");
bw.Flush();
bw.Close();
fs.Close();
}
答案 0 :(得分:0)
这是创建Word文档的一种非常难看的方式..即使它可以工作,您也无法控制您似乎需要的格式。我强烈建议使用一些库来创建真正的word文档,如WordDocumentGenerator或类似文档。
http://worddocgenerator.codeplex.com/
另一种方法可能是使用XSL模板转换从数据库获取的xml数据。
http://securityroots.com/dradispro/support/guides/reports_xslt.html
http://msdn.microsoft.com/en-us/library/ee872374(v=office.12).aspx