在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
protected void ExportExcel(DataTable dt) { string fileName = “FileName”; Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.ApplicationClass(); int rowIndex = 1;//列 int colIndex = 0;//行 excel.Application.Workbooks.Add(true); foreach (DataColumn col in dt.Columns) { colIndex++; excel.Cells[1, colIndex] = col.ColumnName; excel.get_Range(excel.Cells[1, colIndex], excel.Cells[1, colIndex]).HorizontalAlignment = 3;//设置第一行每一列内容居中显示 } foreach (DataRow row in dt.Rows) { rowIndex++; colIndex = 0; for (colIndex = 0; colIndex < dt.Columns.Count; colIndex++) { excel.Cells[rowIndex, colIndex + 1] = row[colIndex].ToString(); excel.get_Range(excel.Cells[rowIndex, colIndex + 1], excel.Cells[rowIndex, colIndex + 1]).HorizontalAlignment = 4;//设置从第二行开始每一列内容右对齐显示 } } excel.Columns.EntireColumn.AutoFit(); excel.Visible = false; excel.ActiveWorkbook.SaveAs(fileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel7, null, null, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null, null); excel.Quit(); excel = null; GC.Collect();//垃圾回收 } }
|
请发表评论