C#导出Excel,并设置简单格式
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();//垃圾回收 } }