[英]How to create an xls file with NPOI?
All I want to do is to create a file with 1 line and few columns to make some test. 我要做的就是创建一个包含1行,几列的文件进行测试。
However I cannot find a simple way to do such a thing. 但是我找不到一种简单的方法来做这种事情。 Most help I found seem to also use a database. 我发现的大多数帮助似乎也使用了数据库。
I found one that doesn't. 我找到了一个没有的。
Trying to create a new .xlsx file using NPOI and write to it 尝试使用NPOI创建新的.xlsx文件并将其写入
However it seems like a little too much for such a simple task. 但是,对于这样一个简单的任务来说似乎有点太多了。 Is there a tool which would allow me to do something as simple as 有没有可以让我做一些简单的事情的工具
Create file
file.cell[0,0] = ...
You could use the EPPlus package. 您可以使用EPPlus软件包。 Find it on NuGet. 在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();
}
EDIT 编辑
Modification to replace worksheet if it already exists. 修改以替换工作表(如果已存在)。
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.