我想使用C#.net将我的数据网格导出到打开办公室电子表格文件而不是microsoft excel。
请帮我解决这个问题。
答案 0 :(得分:1)
编辑:这个答案是在更改问题之前,当问题被标记为asp.net
您只需导出到将在Excel和Open Office中打开的CSV。
代码例如是:
DataTable2CSV(yourDataTableWhichFilledTheGrid, "FileName.csv", ",");
string filename = "FileName.csv";
Response.ContentType = "application/csv";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename);
Response.TransmitFile(filename);
Response.Flush();
Response.End();
DatatableToCSV代码为:
public void DataTable2CSV(DataTable table, string filename, string sepChar)
{
System.IO.StreamWriter writer = default(System.IO.StreamWriter);
try
{
writer = new System.IO.StreamWriter(filename);
// first write a line with the columns name
string sep = "";
System.Text.StringBuilder builder = new System.Text.StringBuilder();
foreach (DataColumn col in table.Columns)
{
builder.Append(sep).Append(col.ColumnName);
sep = sepChar;
}
writer.WriteLine(builder.ToString());
// then write all the rows
foreach (DataRow row in table.Rows)
{
sep = "";
builder = new System.Text.StringBuilder();
foreach (DataColumn col in table.Columns)
{
builder.Append(sep).Append(row[col.ColumnName]);
sep = sepChar;
}
writer.WriteLine(builder.ToString());
}
}
finally
{
if ((writer != null))
writer.Close();
}
}
因此,代码实际上是将yourDataTableWhichFilledTheGrid(一个数据表)导出到一个名为FileName.csv的文件,然后使用Repsonse函数将其发送给用户。
答案 1 :(得分:1)
如果您需要比CSV更精彩的东西,您可以通过XML编写文档。 OpenOffice XML Specification
答案 2 :(得分:1)
您可以选择使用SpreadSheetLight
使用DataGridView,您的代码将如下所示:
SLDocument sl = new SLDocument();
//Read data from grid and write it in excel
for (int rows = 0; rows < dataGrid.Rows.Count; rows++)
{
for (int col= 0; col < dataGrid.Rows[rows].Cells.Count; col++)
{
sl.SetCellValue(rows, col, dataGrid.Rows[rows].Cells[col].Value.ToString());
}
}
sl.SaveAs("Test.xlsx");