zoukankan      html  css  js  c++  java
  • 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();//垃圾回收 
            }
        }
  • 相关阅读:
    DGL学习(六): GCN实现
    DGL学习(五): DGL构建异质图
    DGL学习(四): 图分类教程
    LuoGuP2495:[SDOI2011]消耗战
    LuoGuP1121:环状最大两段子段和
    LuoGuP3177:[HAOI2015]树上染色
    LuoGuP2607:[ZJOI2008]骑士
    HDU4283:You Are the One
    LuoGuP4294:[WC2008]游览计划
    LuoGuP4127:[AHOI2009]同类分布
  • 原文地址:https://www.cnblogs.com/a7265813/p/3638100.html
Copyright © 2011-2022 走看看