不从Gridview到Excel检索数据

时间:2013-08-14 05:29:00

标签: c# winforms sql-server-2008

excel文件中唯一显示的是列名,而不是来自Gridview的数据。

以下是我的功能

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

从SQL调用数据的函数

    private void Details()
    {

        DataTable dt = new DataTable();
        SqlDataAdapter adp = new SqlDataAdapter("SELECT * FROM Customer WHERE CustomerID like " + txtCustomerID.Text, cn);
        adp.Fill(dt);
        gvHistory.DataSource = dt;


    }

这是我在按钮中的代码,用于将来自GridView的数据另存为excel文件。

private void button2_Click(object sender, EventArgs e)
    {
        SaveFileDialog sfd = new SaveFileDialog();
        sfd.Filter = "Excel Documents (*.xls)|*.xls";
        sfd.FileName = "";
        if (sfd.ShowDialog() == DialogResult.OK)
        {
            //ToCsV(dataGridView1, @"c:\export.xls");
            ToCsV(gvHistory, sfd.FileName); // Here dataGridview1 is your grid view name 
        }

    }

1 个答案:

答案 0 :(得分:0)

我认为您的问题出在select语句

尝试类似

的内容
SELECT * FROM Customer WHERE CustomerID like '%" + txtCustomerID.Text + "%'"

除此之外,您可能希望使用DataAdapter Parameters来避免SQL Injection