Modify excel cell

后端 未结 5 1061
轮回少年
轮回少年 2020-12-31 18:54

Good morning, I would like to edit some cells from already existing excell file. I tried use EPPlus and normal OpenXml classes. However I failed. In both situation program w

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-31 19:48

    although this is answered I'll add from my experience.

    It is easier to open the ExcelPackage from FileInfo instead of Stream, then saving becomes simpler.

    FileInfo file = new FileInfo(path);
    
            using (var package = new ExcelPackage(file))
            {
                ExcelWorkbook workBook = package.Workbook;
                ExcelWorksheet currentWorksheet = workBook.Worksheets.SingleOrDefault(w =>  w.Name == "sheet1");
    
                int totalRows = currentWorksheet.Dimension.End.Row;
                int totalCols = currentWorksheet.Dimension.End.Column;
    
                for (int i = 2; i <= totalRows; i++)
                {                   
                    try
                    {
                        currentWorksheet.Cells[i, 1].Value = "AAA";
    
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(String.Format("Error: failed editing  excel. See details: {0}", ex));
                        return;
                    }
                }
    
                package.Save();
    

提交回复
热议问题