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();//垃圾回收 
        }
    }

 

相关文章:

  • 2021-07-08
  • 2022-12-23
  • 2022-12-23
  • 2021-11-13
  • 2022-12-23
  • 2022-12-23
  • 2021-11-27
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-07
  • 2021-11-24
相关资源
相似解决方案