日期:2014-05-18 浏览次数:21046 次
private void ReportOut(string filename,string strsql)
{
//第一步:导出数据表
oracomm.CommandText = strsql;
orareader = oracomm.ExecuteReader();
//第二步:创建excel文件
GC.Collect();
Microsoft.Office.Interop.Excel.Application excel;
Workbook xBk;
Worksheet xSt = null;
excel = new ApplicationClass();
xBk = excel.Workbooks.Add(true);
//第三步:填充excel文件
//定义循环中要使用的变量
int sheetIndex = 1;
int rowIndex = 1;
int colIndex = 1;
while (orareader.Read())
{
//首行时,添加新的工作表,添加标题栏
if (rowIndex == 1)
{
//创建一个Sheet
if (null == xSt)
{
//第一个工作表创建位置
xSt = (Worksheet)xBk.Worksheets[1];
}
else
{
//新的工作表的创建位置
xSt = (Worksheet)xBk.Worksheets.Add(Type.Missing, xSt, 1, Type.Missing);
}
//设置工作表名
xSt.Name = "数据明细" + sheetIndex.ToString();
//填充标题栏
xSt.get_Range(xSt.Cells[1, 1], xSt.Cells[1, orareader.FieldCount + 1]).HorizontalAlignment = XlVAlign.xlVAlignCenter; //设置标题居中对齐
xSt.get_Range(xSt.Cells[1, 1], xSt.Cells[1, orareader.FieldCount + 1]).Font.Bold = true;//设置标题为粗体
for (colIndex = 1; colIndex <= orareader.FieldCount; colIndex++)
{
xSt.Cells[1, colIndex + 1] = orareader.GetName(colIndex - 1);
}
rowIndex++;
}
//填充数据
xSt.Cells[rowIndex, 1] = rowIndex - 1;
for (colIndex = 1; colIndex <= orareader.FieldCount; colIndex++)
{
if (orareader.GetFieldType(colIndex - 1) == System.Type.GetType("System.String"))
{
xSt.Cells[rowIndex, colIndex + 1] = "'" + orareader[colIndex - 1];
}
else
{
xSt.Cells[rowIndex, colIndex + 1] = orareader[colIndex - 1];
}
}
if ((rowIndex - 1) % 100 == 0)
{
txtInfo.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff ") + "已导入数据" + (rowIndex - 1).ToString() + "条!\r\n");
xBk.Save();
}
//如果超过限定行数,添加新表
if (rowIndex >= 60000)
{
//使用最佳宽度
Range allDataWithTitleRange = xSt.get_Range(excel.Cells[1, 1], excel.Cells[rowIndex, colIndex + 1]);
allDataWithTitleRange.Select();
allDataWithTitleRange.Columns.AutoFit();
allDataWithTitleRange.Borders.LineStyle = 1;//将导出Excel加上边框
sheetIndex++;
rowIndex = 1;
}
else
{
rowIndex++;
}
}
//第四步:保存excel文件
xBk.SaveCopyAs("D:\\" + filename + ".xls");
xBk.Close(false, null, null);
excel.Quit();
orarea