您的位置:首页 > 其它

DataTable数据导入Excel(导入到三个工作表)

2011-08-24 09:55 453 查看
Microsoft.Office.Interop.Excel.ApplicationClass xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
#region 新建一个Excel
if (sheetName == "PaymentDetail")//第二次进入时不需要创建Excel
{
xlApp.DefaultFilePath = ConfigurationSettings.AppSettings["ExcelFilesDriver"].ToString();
xlApp.DisplayAlerts = true;
xlApp.SheetsInNewWorkbook = 1;
Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
xlBook.SaveCopyAs("PaymentExport-" + Yok.Components.YokContext.Current.CurrentUser.CompanyID.ToString() + "-" + DateTime.Now.ToString("yyyy-MM-dd") + ".xls");
}
#endregion
string filePath = xlApp.DefaultFilePath + "PaymentExport-" + Yok.Components.YokContext.Current.CurrentUser.CompanyID.ToString() + "-" + DateTime.Now.ToString("yyyy-MM-dd") + ".xls";
object oMissing = System.Reflection.Missing.Value;
xlApp.Visible = false;
xlApp.DisplayAlerts = false;
Microsoft.Office.Interop.Excel.Workbooks oBooks = xlApp.Workbooks;
Microsoft.Office.Interop.Excel._Workbook xlWorkbook = null;
xlWorkbook = oBooks.Open(filePath,oMissing,oMissing,oMissing,oMissing,oMissing,oMissing,
oMissing,oMissing,oMissing,oMissing,oMissing,oMissing,oMissing,oMissing);
Microsoft.Office.Interop.Excel.Worksheet xlWorksheet;
// 添加入一个新的Sheet页。
xlWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkbook.Worksheets.Add(oMissing,oMissing,1,oMissing);
//新加的Sheet页名。
xlWorksheet.Name = sheetName;
#region 导入数据到Excel
//将DataTable的列名导入Excel表第一行
int rowNum = dt.Rows.Count;
int columnNum = dt.Columns.Count;
int rowIndex = 1;
int columnIndex = 0;
foreach (DataColumn dc in dt.Columns)
{
columnIndex++;
xlApp.Cells[rowIndex, columnIndex] = dc.ColumnName;
}
//将DataTable中的数据导入Excel中
for (int i = 0; i < rowNum; i++)
{
rowIndex++;
columnIndex = 0;
for (int j = 0; j < columnNum; j++)
{
columnIndex++;
xlApp.Cells[rowIndex, columnIndex] = dt.Rows[i][j].ToString();
}
}
#endregion
// 保存并关闭这个工作簿。
xlWorkbook.Close(Microsoft.Office.Interop.Excel.XlSaveAction.xlSaveChanges, oMissing, oMissing);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkbook);
xlWorkbook = null;
//结束进程,释放资源
xlApp.Quit();
GC.Collect();
#region 输出IO并提供下载
if (sheetName == "PaymentApprovalDetail")//只有运行第二遍时才打印输出
{

this.btnDeleteTable.Visible = true;
FileInfo Fi = new FileInfo(filePath);
if (Fi.Exists)
{
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
Response.Charset = "GBK";
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=PaymentExport"+ DateTime.Now.ToString("yyyy-MM-dd") + ".xls");
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
}
#endregion
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: