根据使用epplus的值查找excel中的起始行号和最后一行号

我使用EPPLUS将查询结果放入Excel中。 我有一个名为category的列,我需要在每个类别之后插入一个新行以包含小计。

我的Excel看起来像这样

Category | Quantity A | 5 A | 10 A | 3 B | 2 B | 3 C | 2 

唯一的事情就是我们总是从A2开始。 类别A从A2开始,到A4结束,但是假设我们不知道如何得到A的最后一行,所以我可以在它之后插入一行,然后再插入类别B等等。

预期成绩:

 Category | Quantity A | 5 A | 10 A | 3 Total | 18 B | 2 B | 3 Total | 5 C | 2 Total | 2 

查询按要求放置数据:

 sqlcmd = new sqlcommand(query, con); sqlreader = sqlcmd.executereader(); while (sqlreader.read()) { ws.Cells[rownum, 1].Value = sqlreader["Category"]; ws.Cells[rownum, 2].Value = sqlreader["Quantity"]; rownum = rownum + 1; } 

新代码:

 string currentcategory = ""; string newcategory = ""; while (sqlreader.read()) { if (currentcategory == "") { currentcategory= global_dr["category"].ToString(); newcategory= global_dr["category"].ToString(); } else { newcategory= global_dr["category"].ToString(); } if (newcategory == currentcategory) { ws.Cells[rownum, 1].Value = sqlreader["category"]; ws.Cells[rownum, 2].Value = sqlreader["Quantity"]; rownum = rownum + 1; } else { rownum = rownum + 1; ws.Cells[rownum, 1].Value = sqlreader["category"]; ws.Cells[rownum, 2].Value = sqlreader["Quantity"]; rownum = rownum + 1; currentcategory = ""; } } 

上面的代码用于为小计添加一些空行,但有一些错误,这里是一个示例输出

 Category | Quantity A | 5 A | 10 A | 3 B | 2 B | 3 C | 2 D | 1 

预期:

  C | 2 D | 1 

如果类别只有1行,我目前的代码有错误。

更多的编辑:填充数据后添加行解决上述问题。

  int rowstart = 1; while (ws.Cells[rowstart, 1].Value.ToString() != "") { if (ws.Cells[rowstart, 1].Value.ToString() != ws.Cells[rowstart + 1, 1].Value.ToString()) { ws.InsertRow(rowstart + 1, 1); rowstart = rowstart + 2; } else { rowstart = rowstart + 1; } } 

新问题:一旦我到达最后,示例最后一行的文本是10,我会得到一个Object reference not set to an instance of an object的行11 Object reference not set to an instance of an object

以下是一个简单的例子,让你走,这将帮助你如何得到A的最后一行。

  static void Main(string[] args) { ExcelPackage ep = new ExcelPackage(new FileInfo(@"d:\temp\EPTest.xlsx")); ExcelWorksheet ws = ep.Workbook.Worksheets.First(); //Get all the cells with text "A" in column "A" var acells = from cell in ws.Cells["A:A"] where cell.Text.Equals("A") select cell; //To insert row after the last identified "A" increment the row number by 1 ws.InsertRow(acells.Last().End.Row + 1,1); ep.Save(); } 

为了进一步了解和例子访问epplus.codeplex.com

像这样 – 你可能需要做一些debugging,因为我完全生锈的C#

  const long ROW_START = 2; var sqlcmd = new SqlCommand(query, con); var sqlreader = sqlcmd.ExecuteReader(); string c; double q; string curr_c = "~~~~~~~~~"; double tot = 0; long r = 0; long rownum = ROW_START; while (sqlreader.Read()) { q = (double)sqlreader["Quantity"]; c = sqlreader["Category"].ToString(); if (c != curr_c) { if (rownum > ROW_START) { ws.Cells[rownum, 1].Value = "Total"; ws.Cells[rownum, 2].Value = tot; rownum += 1; } curr_c = c; tot = 0; } ws.Cells[rownum, 1].Value = c; ws.Cells[rownum, 2].Value = q; tot += q; rownum += 1; } ws.Cells[rownum, 1].Value = "Total"; ws.Cells[rownum, 2].Value = tot;