如何将datagrid导出为pdf winform

时间:2014-01-17 07:58:58

标签: c# winforms pdf datagridview

我需要将datagridview导出为pdf(.pdf)和word(.doc)文件。所以我尝试下面的代码

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

传递值

  ToExcelSheet(grd_retrn_detail, "E:/export.doc");

工作正常

如果我传递.pdf.its创建文件但我无法打开

  ToExcelSheet(grd_retrn_detail, "E:/export.pdf");

我需要在word和pdf文件中以表格格式插入数据

我犯了错误?感谢..

1 个答案:

答案 0 :(得分:2)

要导出为pdf,请检查answer of this question

单词检查Msdn here