从数据库统计分析并将数据导入Excel速度慢

idtugv 2010-09-22 08:53:10
在统计时,需要用select count(*) 从数据库中读数据,然后写入Excel,但由于统计比较多,循环下来,就要执行上万条select count(*) 语句,使导出的速度特别慢,有没有什么方法可以提高一下导出的速度?我是这样做的,还没写完,有点乱,麻烦帮我看看,怎么提高一下速度
for (j = 0; j < answTDs.Tables[0].Rows.Count; j++)
{
excel.Cells[x + 3 + 2 * j, 2] = answTDs.Tables[0].Rows[j][0];
excel.Cells[x + 3 + 2 * j, 3] = "计数";
excel.Cells[x + 4 + 2 * j, 3] = "比例";
string dad = DateTime.Now.Date.ToShortDateString();

sqlStr = "select COUNT(*) from 提交答案表 where 项目编号='" + myDs.Tables[0].Rows[i][0] + "' and 题号=" + quesDs.Tables[0].Rows[m][1] + " and 选择信息 like '%(17(" + (j + 1) + "))%'";
sqlStr = sqlStr + " and [拨号标记]='完成'and 完成时间 between '" + DateTime.Now.Date.ToShortDateString() + " 00:00:00' and '" + DateTime.Now.Date.ToShortDateString() + " 23:59:59'";
SqlDataAdapter jsDa = new SqlDataAdapter(sqlStr, myConn);
DataSet jsDs = new DataSet();
jsDa.Fill(jsDs);
int total = Convert.ToInt32(jsDs.Tables[0].Rows[0][0]);
int z = 0;
for (z = 0; z < answDs.Tables[0].Rows.Count; z++)
{
sqlStr = "select COUNT(*) from 提交答案表 where 项目编号='" + myDs.Tables[0].Rows[i][0] + "' and 题号=" + quesDs.Tables[0].Rows[m][1] + " and 选择信息 like '%(17(" + (j + 1) + "))%'";
sqlStr = sqlStr + "and 选择项='" + (z + 1) + "' and [拨号标记]='完成'and 完成时间 between '" + DateTime.Now.Date.ToShortDateString() + " 00:00:00' and '" + DateTime.Now.Date.ToShortDateString() + " 23:59:59'";
jsDa = new SqlDataAdapter(sqlStr, myConn);
jsDs = new DataSet();
jsDa.Fill(jsDs);
excel.Cells[x + 3 + 2 * j, 4 + z] = jsDs.Tables[0].Rows[0][0];
double percent = Convert.ToDouble(jsDs.Tables[0].Rows[0][0]) * 100 / Convert.ToDouble(total);
excel.Cells[x + 4 + 2 * j, 4 + z] = percent.ToString("0.0") + "%";
}
excel.Cells[x + 3 + 2 * j, 4 + z] = total;
excel.Cells[x + 4 + 2 * j, 4 + z] = "100.0%";
}
...全文
139 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
idtugv 2010-09-26
  • 打赏
  • 举报
回复
谢谢两位的答案,顺便再问一下,我在导出的时候,去打开了另一个Excel文件时,弹出合并单元格出错,只能保存左上角单元格的数据,两个Excel冲突了,有没有办法在导出的时候锁定Excel呢
w526028188 2010-09-23
  • 打赏
  • 举报
回复
学者!。。。
idtugv 2010-09-23
  • 打赏
  • 举报
回复
12345
wuyq11 2010-09-22
  • 打赏
  • 举报
回复
不需要执行数据查询
object o=new DataTable().Compute("sum(字段)","");
捷哥1999 2010-09-22
  • 打赏
  • 举报
回复
需要注意写入Excel时的效率

如果数据量比较大,最好不要逐个单元格写入,而应该使用数组写入方式:

object[,] objData = new Object[maxRowCountData, maxColumnCountData];

for (int i = 1; i < data.Length - 1; i++)
//给objData 赋值

Excel.Range CurRange = GetRange(x1, y1, x2, y2);//选择要写入的区域

CurRange.Value2 = objData;
捷哥1999 2010-09-22
  • 打赏
  • 举报
回复
写入Excle时,不要一个个写入!
用数组的方式写入!

110,533

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧