Modify excel cell

后端 未结 5 1023
轮回少年
轮回少年 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:26

    //this help you to set cells in file excel : using System.Data.OleDb;

            string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Directory.GetCurrentDirectory() + "/swtlist.xlsx;" +
                         @"Extended Properties='Excel 12.0;HDR=Yes;';Persist Security Info=False;";
    
    
            using (OleDbConnection connection = new OleDbConnection(connString))
            {
                connection.Open();
                try
                {
    
                    OleDbCommand cmd = new OleDbCommand("UPDATE  [Feuil1$]  SET d='yes' ", connection);
    
                      cmd.ExecuteNonQuery();
                    connection.Close();
    
    
                }
                catch (Exception ex) { }
            }
    
    0 讨论(0)
  • 2020-12-31 19:28

    I'm using ClosedXML where updating a cell value is a no-brainer:

    var workbook = new XLWorkbook("HelloWorld.xlsx"); // load the existing excel file
    var worksheet = workbook.Worksheets.Worksheet(1);
    worksheet.Cell("A1").SetValue("Hello World!");
    workbook.Save();
    

    The NuGet package can be found here.

    0 讨论(0)
  • 2020-12-31 19:32

    The problem in both cases is that the modified workbook is not saved back to the stream:

    MemoryStream ms = new MemoryStream();
    using (FileStream fs = File.OpenRead(@"Path\Test.xlsx"))
    using (ExcelPackage excelPackage = new ExcelPackage(fs))
    {
        ExcelWorkbook excelWorkBook = excelPackage.Workbook;
        ExcelWorksheet excelWorksheet = excelWorkBook.Worksheets.First();
        excelWorksheet.Cells[1, 1].Value = "Test";
        excelWorksheet.Cells[3, 2].Value = "Test2";
        excelWorksheet.Cells[3, 3].Value = "Test3";
    
        excelPackage.SaveAs(ms); // This is the important part.
    }
    
    ms.Position = 0;
    return new FileStreamResult(ms, "application/xlsx")
    {
        FileDownloadName = "Tester.xlsx"
    };
    
    0 讨论(0)
  • 2020-12-31 19:33

    You can use the Interop dll's from Microsoft to edit office documents http://msdn.microsoft.com/en-us/library/15s06t57.aspx. Add the "Microsoft.Office.Interop.Excel.dll" to your solution. With this code i've changed 2 cell values.

    static void Main(string[] args)
    {
            Application excel = new Application();
    
            Workbook workbook = excel.Workbooks.Open(@"C:\Users\Martijn\Documents\Test.xlsx", ReadOnly: false, Editable:true);
            Worksheet worksheet = workbook.Worksheets.Item[1] as Worksheet;
            if (worksheet == null)
                return;
    
            Range row1 = worksheet.Rows.Cells[1, 1];
            Range row2 = worksheet.Rows.Cells[2, 1];
    
            row1.Value = "Test100";
            row2.Value = "Test200";
    
    
            excel.Application.ActiveWorkbook.Save();
            excel.Application.Quit();
            excel.Quit();
        }
    

    I've started with Test1 and Test2 wich after the program running changed into the proper values.

    Situation before running code Situation after running code

    0 讨论(0)
  • 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();
    
    0 讨论(0)
提交回复
热议问题