更新Excel文档不会保留文档的内容

时间:2018-11-13 06:23:18

标签: c# epplus

我正在使用此代码更新excel文档,它保存了新数据,但旧数据不再显示,请您帮我只想更新excel文档。

public void addRow(string path,int row, string req)
    {
        var f1 = path + "Reqs.xlsx";

        FileInfo file = new FileInfo(f1);
        var package = new ExcelPackage(file);

            ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
            worksheet.Cells[row, 1].Value = req;
            package.Save();

    }

1 个答案:

答案 0 :(得分:0)

在这里,我采用了Emp列表集合来添加重新编码。

公共类Emp {
    public int ID { get; set; }
public string Name { get; set; }
}

私有静态void AddNewRowsToExcelFile()
{

 IList<Emp> empList = new List<Emp>()
{  
    new Emp(){ ID=1003, Name="Name1"},  
    new Emp(){ ID=1004, Name="Name2"},  
    new Emp(){ ID=1005, Name="Name3"}  
}; 

Excel.Application xlApp = new Excel.Application();  

Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(filePath, 0, false, 5,
    "", "", false,Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, 
    false, 0, true, false, false);  

Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);  

Excel.Range xlRange = xlWorkSheet.UsedRange;  
int rowNumber = xlRange.Rows.Count + 1;  

foreach (Emp emp in empList)  
{  
    xlWorkSheet.Cells[rowNumber, 1] = emp.ID;  
    xlWorkSheet.Cells[rowNumber, 2] = emp.Name;  
    rowNumber++;  
}  

// Disable file override confirmaton message 

xlApp.DisplayAlerts = false;  
xlWorkBook.SaveAs(filePath, Excel.XlFileFormat.xlOpenXMLWorkbook,  
    Missing.Value, Missing.Value, Missing.Value, Missing.Value, 
    Excel.XlSaveAsAccessMode.xlNoChange,  
    Excel.XlSaveConflictResolution.xlLocalSessionChanges, Missing.Value, 
    Missing.Value,  
    Missing.Value, Missing.Value);

xlWorkBook.Close();  
xlApp.Quit();  

Marshal.ReleaseComObject(xlWorkSheet);  
Marshal.ReleaseComObject(xlWorkBook);  
Marshal.ReleaseComObject(xlApp);  

Console.BackgroundColor = ConsoleColor.DarkBlue;  
Console.WriteLine("\nRecords Added successfully...");  
Console.BackgroundColor = ConsoleColor.Black;  

}

添加记录后,它将保存文件而不会要求您确认是否覆盖文件。