0

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] = ...
Cher
  • 2,789
  • 10
  • 37
  • 64

1 Answers1

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();
}
STLDev
  • 5,950
  • 25
  • 36
  • How do you write file a second time, this line throws an exception: ExcelWorksheet xlWorksheet = xlPackage.Workbook.Worksheets.Add("Test"); – Cher Jun 15 '17 at 01:04
  • @Cher what exception are you seeing? Perhaps there already exists a sheet with the same name as the one you're attempting to insert. – STLDev Jun 15 '17 at 20:36
  • thx for anser!! but that is exactly the problem, when I call the method, I would just like to overwrite it if it exist – Cher Jun 15 '17 at 23:00
  • So, by overwrite, you mean you'd like to delete the existing sheet and replace it with a new one? I'll edit my response. – STLDev Jun 16 '17 at 01:29