有关将dataSet转换为Excel的咨询

时间:2014-09-15 12:00:13

标签: c# excel

我有这个代码从dataSet转移到Excel(xlsx)

using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Excel;    

string SQL = "SELECT Store,Zitur FROM CounterG group by Store,Zitur";

var dsView = new DataSet();
using (var adp = new OleDbDataAdapter(SQL, Conn))
    adp.Fill(dsView, "CounterG");

Microsoft.Office.Interop.Excel.Application xla = new Microsoft.Office.Interop.Excel.Application();
xla.Visible = false;

Workbook wb = xla.Workbooks.Add(XlSheetType.xlWorksheet);

Worksheet ws = (Worksheet)xla.ActiveSheet;
ws.Name = "Tab1";

int i = 1;
foreach (DataRow comp in dsView.Tables[0].Rows)
{
    ws.Cells[i, 1] =  comp[0].ToString();
    ws.Cells[i, 2] =  comp[1].ToString();
    i++;
}

if (File.Exists(@"d\DDD.xlsx"))
    File.Delete(@"d:\DDD.xlsx");

//xla.SaveWorkspace(@"d:\DDD.xlsx");
xla.Save(@"d:\DDD.xlsx");

但是我从HRESULT得到了错误" 异常:0x800A03EC "在这一行:xla.Save(@"d:\DDD.xlsx");

我使用.NET Framework 2.0处理WinForm。

1 个答案:

答案 0 :(得分:0)

请尝试使用Workbook.SaveAs,如下所示。您还需要包含Excel.Quit()来释放文件。

//xla.SaveWorkspace(@"d:\DDD.xlsx");
wb.SaveAs(Filename: @"d:\DDD.xlsx", FileFormat: XlFileFormat.xlOpenXMLWorkbook);

xla.Quit(); // Exit Excel releasing the file

根据文档,您不应使用Excel.Application.Save来创建文件:

  

首次保存工作簿时,请使用   Microsoft.Office.Interop.Excel._Workbook.SaveAs()   指定文件名称的方法。