C# 使用NPOI编写文件
当试图从DLL执行更改时,我无法使用NPOI将对xlsx的更改保存到磁盘 我有一组数据,目前正在存储在数据库中,还有一个自己开发的ORM。自主开发的ORM存储在自己的DLL中。我想写一个实用程序,它使用ORM获取数据的子集来读/写数据。我正在使用NPOI(v2.1.3.0)来实现它 实用程序调用如下所示:C# 使用NPOI编写文件,c#,.net,.net-4.5,npoi,C#,.net,.net 4.5,Npoi,当试图从DLL执行更改时,我无法使用NPOI将对xlsx的更改保存到磁盘 我有一组数据,目前正在存储在数据库中,还有一个自己开发的ORM。自主开发的ORM存储在自己的DLL中。我想写一个实用程序,它使用ORM获取数据的子集来读/写数据。我正在使用NPOI(v2.1.3.0)来实现它 实用程序调用如下所示: private void Test_Click(object sender, RoutedEventArgs e) { var model = new Exce
private void Test_Click(object sender, RoutedEventArgs e)
{
var model = new ExcelDal(this.filename);
model.Clients.Save(new Client {
DateOfBirth = DateTime.Now, DisplayName = "Test", Male = true
});
}
我希望我会得到一个xlsx,其中有一个名为“Client”的工作表和一个“DateOfBirth”、“DisplayName”和“Male”的文本列。确实创建了一个文件,但尝试打开它失败。另一方面,如果我用此代码替换该代码,我将得到预期的结果:
private void Test_Click(object sender, RoutedEventArgs e)
{
IWorkbook workbook = new XSSFWorkbook();
ISheet sheet = workbook.CreateSheet("Client");
MainWindow.Create(sheet, 0, "DateOfBirth", "DisplayName", "Male");
MainWindow.Create(sheet, 1, "1900/1/1", "Test", "true");
FileMode mode = File.Exists(this.filename) ? FileMode.Truncate : FileMode.Create;
using (FileStream fs = new FileStream(this.filename, mode, FileAccess.ReadWrite))
{
workbook.Write(fs);
}
}
private static void Create(ISheet sheet, int rowNum, params string[] values)
{
IRow row = sheet.CreateRow(rowNum);
for (int i = 0; i < values.Length; i++)
{
ICell cell = row.CreateCell(i);
cell.SetCellValue(values[i]);
}
}
保存文件的代码如下所示:
public void Save()
{
FileMode mode = File.Exists(this.filename) ? FileMode.Truncate : FileMode.Create;
using (FileStream fs = new FileStream(this.filename, mode, FileAccess.ReadWrite))
{
this.workbook.Write(fs);
}
}
我看不出有什么不同。唯一可能的是,一个人通过前面提到的ORM间接地使用NPOI,而另一个人则直接使用它。我无法找到一种可靠地使用NPOI的方法。该实用程序创建的文件总是被破坏。我将xlsx切换到EPPlus。生成的代码如下所示:
public void SetValue(int row, string column, string value)
{
row += 2; //EPPlus is 1-index based, and the first row is the heading
int columnIndex = this.GetColumnIndex(column);
this.excelSheet.SetValue(row, columnIndex, value);
}
public void Dispose()
{
//ExcelPackage is gone once it is written out. It must be re-created.
this.excelPackage.SaveAs(new FileInfo(this.filename));
this.excelPackage.Dispose();
}
保存文件的相应代码如下所示:
public void SetValue(int row, string column, string value)
{
row += 2; //EPPlus is 1-index based, and the first row is the heading
int columnIndex = this.GetColumnIndex(column);
this.excelSheet.SetValue(row, columnIndex, value);
}
public void Dispose()
{
//ExcelPackage is gone once it is written out. It must be re-created.
this.excelPackage.SaveAs(new FileInfo(this.filename));
this.excelPackage.Dispose();
}
因此,实现是添加一个Flush(),它将处理当前的ExcelPackage,然后处理当前内存中的所有ExcelSheet,然后重新初始化写入的文件中的所有内容