簡體   English   中英

如何使用NPOI創建xls文件?

[英]How to create an xls file with NPOI?

我要做的就是創建一個包含1行,幾列的文件進行測試。

但是我找不到一種簡單的方法來做這種事情。 我發現的大多數幫助似乎也使用了數據庫。

我找到了一個沒有的。

嘗試使用NPOI創建新的.xlsx文件並將其寫入

但是,對於這樣一個簡單的任務來說似乎有點太多了。 有沒有可以讓我做一些簡單的事情的工具

Create file
file.cell[0,0] = ...

您可以使用EPPlus軟件包。 在NuGet上找到它。

string fileName = @"C:\test\MyNewExcelFile.xlsx";
FileInfo newFile = new FileInfo(fileName);
using (ExcelPackage xlPackage = new ExcelPackage(newFile)) // create the xlsx file
{
    // Add a new worksheet on which to put data 
    ExcelWorksheet xlWorksheet = xlPackage.Workbook.Worksheets.Add("Test");
    // Write data to cell(s)
    xlWorksheet.Cells["A1"] = ...
    // Write the file
    xlPackage.Save();
}

編輯

修改以替換工作表(如果已存在)。

const string fileName = @"C:\test\MyNewExcelFile.xlsx";
const string sheetName = @"test";

FileInfo newFile = new FileInfo(fileName);

using (ExcelPackage xlPackage = new ExcelPackage(newFile)) // create the xlsx file
{
    // if sheet already exists, delete it
    // use LINQ to query collection of worksheets
    ExcelWorksheet xlWorksheet = xlPackage.Workbook.Worksheets.SingleOrDefault(ws => ws.Name == sheetName);
    if (xlWorksheet != null)
    {
        // worksheet exists - delete it
        xlPackage.Workbook.Worksheets.Delete(sheetName);
    }
    // Add new worksheet on which to put data 
    ExcelWorksheet xlWorksheet = xlPackage.Workbook.Worksheets.Add("Test");
    // Write data to cell(s)
    xlWorksheet.Cells["A1"] = ...
    // Write the file
    xlPackage.Save();
}

暫無
暫無

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

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