我正在使用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,我将为第11行获得Object reference not set to an instance of an object
答案 0 :(得分:1)
以下是一个简单的示例,帮助您了解如何获取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
答案 1 :(得分:0)
这样的事情 - 你可能需要做一些调试,因为我在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;