簡體   English   中英

如何使用C#和ClosedXML將新行附加到Excel文件?

[英]How to append a new row to an Excel file using C# and ClosedXML?

我應該在現有的Excel文件中添加一個新行。 該任務由兩部分組成:

  1. 添加到不存在的文件(效果很好)。
  2. 添加到現有文件(不起作用:它不會創建新記錄,僅顯示“else”正文中的舊記錄)。

這是我的代碼:

private static void ExportToEXCEL(DataTable dt, string paymentStoryPath)
{
    if (File.Exists(paymentStoryPath))
    {
        XLWorkbook currentWorkbook = new XLWorkbook(paymentStoryPath);
        IXLWorksheet currentWsh = currentWorkbook.Worksheet("Payment history");
        //IXLCell cellForNewData = index.Cell(index.LastRowUsed().RowNumber() + 1, 1);
        IXLRow rowForNewData = currentWsh.Row(currentWsh.LastRowUsed().RowNumber()+1);
        rowForNewData.InsertRowsBelow(1);
        rowForNewData.Value = dt;
        currentWorkbook.Save();
    }
    else
    {
        //not exist
        XLWorkbook wb = new XLWorkbook();
        wb.Worksheets.Add(dt, "Payment history");
        wb.SaveAs(paymentStoryPath);
    }
}

有什么問題,我的代碼應該改變什么?

要添加DataTable使用InsertTable()方法:

    XLWorkbook currentWorkbook = new XLWorkbook(paymentStoryPath);
    IXLWorksheet currentWsh = currentWorkbook.Worksheet("Payment history");
    IXLCell cellForNewData = currentWsh.Cell(currentWsh.LastRowUsed().RowNumber() + 1, 1);
    cellForNewData.InsertTable(dt);
    currentWorkbook.Save();

我從我的一個將DataTable插入Excel的項目中獲得了以下代碼。

//insert rows below a range from the cell going table rows down
ws.Range(
    cell.Address.RowNumber
    , cell.Address.ColumnNumber
    , cell.Address.RowNumber + DocDataSet.Tables[tableNo].Rows.Count
    , cell.Address.ColumnNumber)
    .InsertRowsBelow(DocDataSet.Tables[tableNo].Rows.Count);

//InsertData returns a range covering the inserted data
var ra = ws.Cell(cell.Address.RowNumber, cell.Address.ColumnNumber)
    .InsertData(DocDataSet.Tables[tableNo].AsEnumerable());

//apply the style of the table token cell to the whole range
ra.Style = cell.Style;

自從我編寫它以來已經有一段時間了,但據我所知,創建一個范圍將覆蓋將填充的行和列。 Cell對象有一個InsertData方法,可以接受任何IEnumerable源。

你可能不需要ws.Range行,我插入模板所以我必須先創建空間。

我拿了@raidri的例子,然后又向前邁了一步,我有一個擴展方法來處理這個問題。

public static class Extensions
{
    public static void ToExcelFile(this DataTable dataTable, string filename, string worksheetName = "Sheet1")
    {
        using(var workbook = new XLWorkbook())
        {
            workbook.Worksheets.Add(dataTable, worksheetName);

            workbook.SaveAs(filename);
        }
    }
}

使用

myDataTable.ToExcelFile(@"C:\temp\myFile.xlsx");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM