瀏覽代碼

Added headerRowIndex, #4

Piotr Czajkowski 5 月之前
父節點
當前提交
f77a1feac8
共有 3 個文件被更改,包括 8 次插入6 次删除
  1. 5 4
      ExcelORM/ExcelORM/ExcelWriter.cs
  2. 3 2
      ExcelORM/ExcelORMTests/WriterTests.cs
  3. 二進制
      ExcelORM/ExcelORMTests/testFiles/forAppend.xlsx

+ 5 - 4
ExcelORM/ExcelORM/ExcelWriter.cs

@@ -71,7 +71,7 @@ public class ExcelWriter
         }
     }
 
-    private static void Write<T>(IEnumerable<T> values, IXLWorksheet worksheet, bool append) where T : class
+    private static void Write<T>(IEnumerable<T> values, IXLWorksheet worksheet, bool append, uint? headerRowIndex = null) where T : class
     {
         if (!values.Any()) return;
 
@@ -82,7 +82,8 @@ public class ExcelWriter
         if (append)
         {
             rowIndex = worksheet.LastRowUsed().RowNumber() + 1;
-            mapping = Mapping.MapProperties<T>(worksheet.FirstRowUsed().CellsUsed());
+            var headerCells = headerRowIndex != null ? worksheet.Row((int)headerRowIndex).CellsUsed() : worksheet.FirstRowUsed().CellsUsed();
+            mapping = Mapping.MapProperties<T>(headerCells);
             if (mapping == null || mapping.Count == 0) return;
         } else
             rowIndex = GenerateHeader<T>(worksheet);
@@ -96,7 +97,7 @@ public class ExcelWriter
         }
     }
 
-    public void Write<T>(IEnumerable<T> values, string? worksheetName = null, bool append = false) where T : class
+    public void Write<T>(IEnumerable<T> values, string? worksheetName = null, bool append = false, uint? headerRowIndex = null) where T : class
     {
         var xlWorksheet = xlWorkbook.Worksheets.FirstOrDefault(x => x.Name.Equals(worksheetName, StringComparison.InvariantCultureIgnoreCase));
         
@@ -104,7 +105,7 @@ public class ExcelWriter
             xlWorkbook.AddWorksheet(worksheetName)
             : xlWorkbook.Worksheets.Count == 0 ? xlWorkbook.AddWorksheet() : xlWorkbook.Worksheets.First();
 
-        Write(values, xlWorksheet, append);
+        Write(values, xlWorksheet, append, headerRowIndex);
     }
 
     public void SaveAs(string path, IExcelConverter? converter = null)

+ 3 - 2
ExcelORM/ExcelORMTests/WriterTests.cs

@@ -75,12 +75,13 @@ public class WriterTests
         testFile = Path.ChangeExtension(testFile, "xlsx");
         File.Copy(ForAppend, testFile);
 
+        uint headerRowIndex = 3;
         var writer = new ExcelWriter(testFile);
-        writer.Write(arrayOfThree, append: true);
+        writer.Write(arrayOfThree, append: true, headerRowIndex: headerRowIndex);
         writer.SaveAs(testFile);
 
         var reader = new ExcelReader(testFile);
-        var readArray = reader.Read<Test>().ToArray();
+        var readArray = reader.Read<Test>(startFrom: headerRowIndex).ToArray();
         Assert.Equal(6, readArray.Length);
 
         for (int i = 0; i < arrayOfThree.Length; i++)

二進制
ExcelORM/ExcelORMTests/testFiles/forAppend.xlsx