All I want to do is to create a file with 1 line and few columns to make some test.
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
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. Find it on 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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.