我有一个包含帐单详细信息的datagridview。还有一个包含总金额的标签。我想在Excel中将datagridview值添加到excel和datagridview值末尾的标签总数。
这里我使用一个函数将datagridview导出到excel。并在点击事件中调用它。
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();
}
现在我想将标签值添加到excel数据的末尾。我看过添加标签值的示例。但我的问题是我想在excel中的数据末尾添加它。所以它可以称为总数。我怎样才能做到这一点。我坚持了下来。有人能帮助我吗?
答案 0 :(得分:0)
考虑从DataTable
填充数据网格视图。您可以使用开源的EPPlus
库。从网上下载并在您的应用程序中引用。这是代码..
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode("Logs.xlsx", System.Text.Encoding.UTF8));
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Logs");
ws.Cells["A1"].LoadFromDataTable(dt, true);
//Here you can add your Label value to whatever cells you want..for example- A1 or something
var ms = new System.IO.MemoryStream();
pck.SaveAs(ms);
ms.WriteTo(Response.OutputStream);
}