mini-software / MiniExcel

Fast, Low-Memory, Easy Excel .NET helper to import/export/template spreadsheet (support Linux, Mac)
https://www.nuget.org/packages/MiniExcel/
Apache License 2.0
2.81k stars 342 forks source link

MiniExcel.Insert()方法无法正常追加CSV文件 #643

Closed C-Li closed 3 months ago

C-Li commented 3 months ago

Excel Type

Upload Excel File

Please attach your issue file by dragging or droppng, selecting or pasting them.

test.csv

MiniExcel Version

1.34.0.0

Description

照示例写了CSV追加的程序,但似乎只能从第一行开始追加,会覆盖原有的数据。 image

string filePath = Path.Combine(CommonHelper.GetBaseDataDirectory(), "test.csv");
var objList = new[] {
                      new { ID=1,Name ="Frank",InDate=new DateTime(2021,06,07)},
                      new { ID=2,Name ="Gloria",InDate=new DateTime(2022,05,03)},
                };
using (var stream = File.OpenWrite(filePath))
{
    MiniExcel.SaveAs(stream, objList, true, "data", ExcelType.CSV);
}
objList = new[] {
                  new { ID=3,Name ="Frank",InDate=new DateTime(2021,06,07)},
                  new { ID=4,Name ="Gloria",InDate=new DateTime(2022,05,03)},
            };
using (var stream = File.OpenWrite(filePath))
{
    MiniExcel.Insert(stream, objList, "data", ExcelType.CSV);
}

执行的结果: image

而且这里的 Insert 必须指明是 ExcelType.CSV ,不然会报错: System.NotImplementedException:“未实现该方法或操作。”

izanhzh commented 3 months ago

在insert前加语句将流的当前位置设置到流的末尾:

stream.Seek(0, SeekOrigin.End);

或者不要用File.OpenWrite,改为:

var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read, 4096, FileOptions.SequentialScan)