从字符串值创建实例

时间:2015-08-06 08:40:15

标签: asp.net c#-4.0

大家好我有以下代码可以正常使用

using (ExcelPackage package = new ExcelPackage(newFile))
{
    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Company1");
    //Add the headers
    worksheet.Cells[1, 1].Value = "ServiceNo";
    worksheet.Cells[1, 2].Value = "AccountNo";
    worksheet.Cells[1, 3].Value = "Service";
    worksheet.Cells[1, 4].Value = "CostCentre";
    //Add some items...
    int x = 2;
    worksheet.Cells["A" + x.ToString()].Value = 12001;
    worksheet.Cells["B" + x.ToString()].Value = "Nails";
    worksheet.Cells["C" + x.ToString()].Value = 37;
    worksheet.Cells["D" + x.ToString()].Value = 3.99;
    package.Save();
}

但我想以编程方式添加多个工作表

List<string> compCodes = new List<string>();
//loop through records in db
compCodes.Add("comp1");
compCodes.Add("comp2");

using (ExcelPackage package = new ExcelPackage(newFile))
{
    add a new worksheet to the empty workbook
    foreach (string comp in compCodes)
    {
        string company = "company" + comp;
        ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(company);
        //Add the headers
        worksheet.Cells[1, 1].Value = "ServiceNo";
        worksheet.Cells[1, 2].Value = "AccountNo";
        worksheet.Cells[1, 3].Value = "Service";
        worksheet.Cells[1, 4].Value = "CostCentre";
        worksheet.Cells[1, 5].Value = "Usage";
        worksheet.Cells[1, 6].Value = "Usage";
        worksheet.Cells[1, 7].Value = "GrossRecurring";
        worksheet.Cells[1, 8].Value = "OneOffCharge";
        worksheet.Cells[1, 9].Value = "Adjustments";
        worksheet.Cells[1, 10].Value = "Discount";
        worksheet.Cells[1, 11].Value = "TotalExVAT";
        worksheet.Cells[1, 12].Value = "VAT";
        worksheet.Cells[1, 13].Value = "Total";
        worksheet.Cells[1, 14].Value = "Source Bill Ref";
        int x = 1;
        worksheet.Cells["A" + x.ToString()].Value = 12001;
        worksheet.Cells["B" + x.ToString()].Value = "Nails";
        worksheet.Cells["C" + x.ToString()].Value = 37;
        worksheet.Cells["D" + x.ToString()].Value = 3.99;
    }
    package.Save();
}

我认为它有效,但在尝试保存

时会抛出错误

保存文件C:\ inetpub \ download.xlsx

时出错

任何人都可以提供帮助

1 个答案:

答案 0 :(得分:0)

c:\ inetpub是通过IIS托管的任何网站的默认站点文件夹。默认情况下,Web应用程序(&amp; Web服务器)配置为无法访问计算机上的本地文件系统。

您可能需要使用MSDN的官方文档为网站文件夹创建访问规则

https://msdn.microsoft.com/en-us/library/vstudio/t32yf0a9(v=vs.100).aspx

根据您正在使用的身份验证类型,可能会有其他步骤适用于同一页面。