简体   繁体   English

如何为Excel表格单元格设置值

[英]How to Set Values To Excel Sheet Cells

I am trying to set an Excel sheet specific cells starting at column A and second Excel sheet row. 我试图设置从A列和第二个Excel工作表行开始的Excel工作表特定的单元格。 I wrote the following code: 我写了以下代码:

if (!File.Exists(AppConfiguration.FilePath))
{
    throw new FileNotFoundException("File Not Found. The requested template.xlsx was not found on the server");
}

Microsoft.Office.Interop.Excel.Application xlsx = new Microsoft.Office.Interop.Excel.Application();
Workbook workbook = null;

try
{
    workbook = xlsx.Workbooks.Open(AppConfiguration.FilePath, ReadOnly: false, Editable: true);
    Worksheet worksheet = workbook.Worksheets[1];
    Microsoft.Office.Interop.Excel.Range cells = worksheet.Cells["$A"];
    List<Analytics> list = (List<Analytics>)data;

    for (int i = 0; i < list.Count; i++)
    {
        ((Microsoft.Office.Interop.Excel.Range)cells[i + 1, 0]).Value = list[i].ProductShare;
        ((Microsoft.Office.Interop.Excel.Range)cells[i + 1, 1]).Value = list[i].MarketPotential;
    }

    workbook.Save();
}
catch(Exception e)
{
    throw new Exception("Error while processing file");
}
finally
{
    workbook.Close(SaveChanges: true);
    xlsx.Quit();
    Marshal.ReleaseComObject(workbook);
}

However, I always get an Exception at 但是,我总是在

(Microsoft.Office.Interop.Excel.Range)cells[i + 1, 0]).Value = list[i].ProductShar

在Excel中,索引以1开头,因此cells[i + 1, 0]无效,请改用cells[i + 2, 1]

for(int i = 0; i< list.Count; i++)
{
   worksheet.Range[string.Format("A{0}", i + 2].Value = list[i].val;
}

Starting at A2 I begin to write the values within my list which is what I was seeking for! 从A2开始,我开始在列表中写入要查找的值! Thanks for all of you for your times and considerations! 感谢大家的宝贵时间和考虑!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM