在word文件中的表中的每个单元格中显示每个导出的记录

时间:2014-03-26 06:31:29

标签: c# sql button gridview

我已将gridview中的数据导出为与gridview中相同的单词。

但是我需要在导出

时显示单词中不同单元格中的每条记录

M在dot net中使用Windows应用程序

从gridview导出数据时输出了输出 -----比尔细节-----

ID名称位置
1 rasdf sdf
2 sdf jlkj
3 dfdf dfdf
4 dsaf sdfdsfds
5孟买国王

这就像有4个柱子的桌子......我需要像这样的输出

1 rasdf sdf 2 sdf jlkj 3 dfdf dfdf 4 dsaf sdfdsfds
5孟买国王

此代码以导出按钮

编写
private void Eportto work(object sender, EventArgs e)
        {
            sfd.Filter = "Excel Documents (*.doc)|*.doc";

            if (sfd.ShowDialog() == DialogResult.OK)
             {
              ExportToWord(); 
                } 
        }


private void ExportToWord()
        {

            string strForPrint = "";


                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();
        }

2 个答案:

答案 0 :(得分:0)

尝试使用此示例实现:

为了从C#windows应用程序将数据插入到word表中,您可以参考下面共享的链接:

msdn link

答案 1 :(得分:0)

更改strForPrint + = strLineData +&#34; \ r \ n&#34 ;;内部for循环 - &gt; for(int i = 0; i&lt; dataGridView1.RowCount - 1; i ++)

 If(strForPrint%4==0)//4 rows has been added
 {
   strForPrint += strLineData + "\r\n"; //go to new line
 }
 else {
  strLineData = strLineData + "\t\t"; //4 rows not added stay on same line
 }

希望这个逻辑清晰