招呼好人。希望大家一切都好。
我有一个Datagridview,它可以填充数据库中的数据并将数据从datagridview中导出为excel文件。
当我将数据导出为Excel文件时。它包含带有datagrdiview标头的数据,但是当导出时,我还需要在我的excel文件中添加标头标题和地址。不在datagridview中。我怎样才能做到这一点?我尝试了Google的许多东西。注意到作品。我当前的源代码(只是将数据导出为excel文件)如下:
private void btnExcel_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel Document(*.xls)|*.xls";
sfd.FileName = "export.xls";
if (sfd.ShowDialog()==DialogResult.OK)
{
ToExcel(dgvPendingPR,sfd.FileName);
}
}
private void ToExcel ( DataGridView dgv,string filename)
{
string stOutput = "";
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";
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);
bw.Flush();
bw.Close();
fs.Close();
}