美文网首页
C#导出数据到Excel表

C#导出数据到Excel表

作者: 是不可谓也 | 来源:发表于2018-01-23 16:16 被阅读18次
    private void GenerateAttachment1(DataTable DT)
    {
        try
        {
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            if (app == null)
            {
                untCommon.InfoMsg("服务器上缺少Excel组件,需要安装Office软件后重试");
                return;
            }
            app.Visible = false;
            app.UserControl = true;
    
            string strTempPath = @"D:\!ZhengkuiD\Defence\DefenceMgr\bin\Debug\goodExcel\Old\XXXX.xlsx";  //模板Excel文件的路径
            Microsoft.Office.Interop.Excel.Workbooks workbooks = app.Workbooks;
            Microsoft.Office.Interop.Excel._Workbook workbook = workbooks.Add(strTempPath); //加载模板
            Microsoft.Office.Interop.Excel.Sheets sheets = workbook.Sheets;
            Microsoft.Office.Interop.Excel._Worksheet worksheet = (Microsoft.Office.Interop.Excel._Worksheet)sheets.get_Item(1); //第一个工作薄
            if (worksheet == null)  //工作薄中没有工作表
            {
                return;
            }
    
            //1、获取数据
            int rowCount = DT.Rows.Count;
            if (rowCount <= 0)
                return;
    
            //2、写入数据,Excel索引从1开始
            for (int i = 1; i <= rowCount; i++)
            {
                int row_ = 0;
                row_ = 3 + i;  //Excel模板上隐藏标题、表头和标题行共占3行,根据实际模板需要修改
    
                int dt_row = i - 1; //dataTable的行是从0开始的 
    
                //开始赋值
                worksheet.Cells[row_, 1] = i.ToString();
                worksheet.Cells[row_, 2] = DT.Rows[dt_row]["Name"].ToString();
            }
    
            //3、保存生成的Excel文件
            string savePath = @"D:\!ZhengkuiD\Defence\DefenceMgr\bin\Debug\goodExcel\New\XXXX.xlsx";
            workbook.SaveAs(savePath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
    
            shuzi++;
    
            //4、按顺序释放资源
            NAR(worksheet);
            NAR(sheets);
            NAR(workbook);
            NAR(workbooks);
            app.Quit();
            NAR(app);
        }
        catch (Exception)
        {
    
        }
    }

    相关文章

      网友评论

          本文标题:C#导出数据到Excel表

          本文链接:https://www.haomeiwen.com/subject/gqwsaxtx.html