1

我正在尝试将我网站中的数据集导出到 Excel。该代码在本地计算机上运行良好,但是当我部署相同的代码以取胜时。服务器即时收到以下错误:

在此处输入图像描述

我正在使用以下代码:

    DataSet ds = new DataSet("New_DataSet");
    DataTable dt = new DataTable("New_DataTable");

    string constr = ConfigurationSettings.AppSettings["ConnectionInfo"];
    SqlConnection con = new SqlConnection(constr);
    con.Open();

    string sql = "SELECT * FROM Table1";
    SqlCommand cmd = new SqlCommand(sql, con);
    SqlDataAdapter adptr = new SqlDataAdapter();

    adptr.SelectCommand = cmd;
    adptr.Fill(dt);
    con.Close();

    ds.Tables.Add(dt);
    MyExcel.Application oXL;
    MyExcel.Workbook oWB;
    MyExcel.Worksheet oSheet;
    MyExcel.Range oRange;

// 工作表 sheet = excelApp.Worksheets; // <-- 重要部分 //Worksheet sheet = sheet.Open(...);

    oXL = new MyExcel.Application();

    oXL.Visible = true;
    oXL.DisplayAlerts = false;
    oWB = oXL.Workbooks.Add(System.Type.Missing);
    //oWB = oXL.Workbooks.Add(System.Type.Missing);

    oSheet = (MyExcel.Worksheet)oWB.ActiveSheet;
    oSheet.Name = "Customers";

    int rowCount = 1;
    foreach (DataRow dr in dt.Rows)
    {
        rowCount += 1;
        for (int i = 1; i < dt.Columns.Count + 1; i++)
        {
            // Add the header the first time through 
            if (rowCount == 2)
            {
                oSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
            }
            oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
        }
    }

    // Resize the columns 
    oRange = oSheet.get_Range(oSheet.Cells[1, 1],
                  oSheet.Cells[rowCount, dt.Columns.Count]);
    oRange.EntireColumn.AutoFit();

    // Save the sheet and close 


    oWB.SaveAs("test.xlsx", MyExcel.XlFileFormat.xlWorkbookNormal, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing,
        MyExcel.XlSaveAsAccessMode.xlExclusive, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);

    oSheet = null;
    oRange = null;
    oWB = null;
    oXL = null;

     oWB.Close(false, System.Type.Missing, System.Type.Missing);
    Marshal.FinalReleaseComObject(oWB);
    Marshal.FinalReleaseComObject(oXL);

    oXL.Quit();
    Marshal.ReleaseComObject(oSheet);
    Marshal.ReleaseComObject(oSheet);


    GC.WaitForPendingFinalizers();
    GC.Collect();
    GC.WaitForPendingFinalizers();
    GC.Collect();

我没有得到任何解决方案。任何人都可以帮忙吗?

4

1 回答 1

2

如果您已检查是否有足够的可用空间,那么唯一可能的另一个问题是权限。

希望您发现此链接有用:

http://www.codeproject.com/Questions/87128/Unable-to-write-data-runtime-in-Excel-app-using-c

于 2012-12-07T09:34:06.027 回答