使用Office组件导出Excel表格

//合并单元格(参数为:sheet、起始单元格、结束单元格、单元格数据、字体大小(默认为9))其他需要单独控制的都可以加参数
        private void RangeBuild(_Worksheet oSheet, string startcell, string endcell, string value, int fontsize = 9)
        {
            ///创建一个区域对象。第一个参数是开始格子号,第二个参数是终止格子号。比如选中A1——D3这个区域。
            Range range = (Range)oSheet.get_Range(startcell, endcell);
            ///合并方法,0的时候直接合并为一个单元格
            range.Merge(0);
            //可以换行
            range.WrapText = true;
            ///合并单元格之后,设置其中的文本
            range.Value = value;
            //横向居中
            range.HorizontalAlignment = XlVAlign.xlVAlignCenter;
            ///字体大小
            range.Font.Size = fontsize;
            ///行高
            range.RowHeight = 20;
            //自动调整列宽
            //range.EntireColumn.AutoFit();
            //列宽
            range.ColumnWidth = 3.2;
            //填充颜色
            //range.Interior.ColorIndex = 20;
            //给单元格加边框
            range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThin, XlColorIndex.xlColorIndexAutomatic, System.Drawing.Color.Black.ToArgb());    
        }

/// <summary>

/// 将DataTable中的数据输出保存为Excel表格

/// </summary>

/// <param name="dt"></param>

protected void ExportExcel(System.Data.DataTable dt, string strFilePath, string strSheetName,string AsmName,string tuhao)
        {
            if (dt == null || dt.Rows.Count == 0) return;

Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

if (xlApp == null)
            {
                return;
            }

xlApp.DisplayAlerts = false;
            System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;

System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;

Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);

Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];

//根据数据和每个sheet页的大小判断需要多少个sheet页
            int nPage = 0;
            int nSize = 42;

if (dt.Rows.Count % nSize == 0)
            {
                nPage = dt.Rows.Count / nSize;
            }
            else
            {
                nPage = dt.Rows.Count / nSize + 1;
            }

//大于一页就得多加Sheet
            if (nPage > 1)
            {
                for (int k = 1; k < nPage; k++)
                {
                    workbook.Sheets.Add(Type.Missing, (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[k], 1, Type.Missing);
                }
            }

Range range = null;
            Worksheet Activesheet = null;
            for (int j = 1; j <= nPage; j++)
            {
                //每页的都要加表头
                Activesheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[j];

RangeBuild(Activesheet, "A1", "C1", "");
                RangeBuild(Activesheet, "A2", "C2", "");
                RangeBuild(Activesheet, "A1", "A2", "公司名称或者项目名称", 8);

RangeBuild(Activesheet, "D1", "O1", "明细表", 10);

RangeBuild(Activesheet, "P1", "S1", tuhao);
                RangeBuild(Activesheet, "T1", "T1", "MX");
                RangeBuild(Activesheet, "D2", "I2", "项目名称", 10);
                RangeBuild(Activesheet, "J2", "O2", AsmName, 10);

RangeBuild(Activesheet, "P2", "R2", string.Format("共{0}页",nPage));
                RangeBuild(Activesheet, "S2", "T2", string.Format("第{0}页",j));

RangeBuild(Activesheet, "A3", "A5", "制表");
                RangeBuild(Activesheet, "B3", "B5", "");
                RangeBuild(Activesheet, "C3", "C5", "校队");

RangeBuild(Activesheet, "D3", "F3", "");
                RangeBuild(Activesheet, "D4", "F4", "");
                RangeBuild(Activesheet, "D5", "F5", "");
                RangeBuild(Activesheet, "D3", "F5", "");

RangeBuild(Activesheet, "G3", "G3", "标记");
                RangeBuild(Activesheet, "H3", "H3", "处数");

RangeBuild(Activesheet, "I3", "K3", "许可编号");

RangeBuild(Activesheet, "L3", "L3", "签名");
                RangeBuild(Activesheet, "M3", "O3", "日期");

RangeBuild(Activesheet, "G4", "G4", "");
                RangeBuild(Activesheet, "G5", "G5", "");

RangeBuild(Activesheet, "H4", "H4", "");
                RangeBuild(Activesheet, "H5", "H5", "");

RangeBuild(Activesheet, "I4", "K4", "");
                RangeBuild(Activesheet, "I5", "K5", "");

RangeBuild(Activesheet, "L4", "L4", "");
                RangeBuild(Activesheet, "L5", "L5", "");

RangeBuild(Activesheet, "M4", "O4", "");
                RangeBuild(Activesheet, "M5", "O5", "");

RangeBuild(Activesheet, "P3", "T3", "");
                RangeBuild(Activesheet, "P4", "T4", "");
                RangeBuild(Activesheet, "P5", "T5", "");
                RangeBuild(Activesheet, "P3", "P5", "日期");

RangeBuild(Activesheet, "A6", "A7", "序号");

RangeBuild(Activesheet, "B6", "G6", "");
                RangeBuild(Activesheet, "B7", "G7", "");
                RangeBuild(Activesheet, "B6", "B7", "代号");

RangeBuild(Activesheet, "H6", "K6", "");
                RangeBuild(Activesheet, "H7", "K7", "");
                RangeBuild(Activesheet, "H6", "H7", "名称及规格");

RangeBuild(Activesheet, "L6", "L7", "数量");

RangeBuild(Activesheet, "M6", "O6", "");
                RangeBuild(Activesheet, "M7", "O7", "");
                RangeBuild(Activesheet, "M6", "M7", "材料");

RangeBuild(Activesheet, "P6", "Q6", "单重");
                RangeBuild(Activesheet, "R6", "S6", "总重");

RangeBuild(Activesheet, "P7", "S7", "公斤");

RangeBuild(Activesheet, "T6", "T7", "备注");

for (int r = nSize * (j - 1); r <= nSize * j - 1; r++)
                {
                    if (r < dt.Rows.Count)
                    {
                        int nstart = r + 8 - nSize * (j - 1);
                        range = (Microsoft.Office.Interop.Excel.Range)Activesheet.Cells[nstart, 1];
                        range.Value = dt.Rows[r][0].ToString();
                        //横向居中
                        range.HorizontalAlignment = XlVAlign.xlVAlignCenter;
                        range.EntireColumn.AutoFit();
                        range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThin, XlColorIndex.xlColorIndexAutomatic, System.Drawing.Color.Black.ToArgb());     //给单元格加边框

range = (Range)Activesheet.get_Range(string.Format("B{0}", nstart), string.Format("G{0}", nstart));
                        range.Merge(0);
                        range.Value = dt.Rows[r][1].ToString();
                        //range.HorizontalAlignment = XlVAlign.xlVAlignCenter;
                        range.EntireColumn.AutoFit();
                        range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThin, XlColorIndex.xlColorIndexAutomatic, System.Drawing.Color.Black.ToArgb());     //给单元格加边框

range = (Range)Activesheet.get_Range(string.Format("H{0}", nstart), string.Format("K{0}", nstart));
                        range.Merge(0);
                        range.Value = dt.Rows[r][2].ToString();
                        //range.HorizontalAlignment = XlVAlign.xlVAlignCenter;
                        range.EntireColumn.AutoFit();
                        range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThin, XlColorIndex.xlColorIndexAutomatic, System.Drawing.Color.Black.ToArgb());     //给单元格加边框

range = (Range)Activesheet.get_Range(string.Format("L{0}", nstart));
                        range.Value = dt.Rows[r][3].ToString();
                        //横向居中
                        range.HorizontalAlignment = XlVAlign.xlVAlignCenter;
                        range.EntireColumn.AutoFit();
                        range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThin, XlColorIndex.xlColorIndexAutomatic, System.Drawing.Color.Black.ToArgb());     //给单元格加边框

range = (Range)Activesheet.get_Range(string.Format("M{0}", nstart), string.Format("O{0}", nstart));
                        range.Merge(0);
                        range.Value = dt.Rows[r][4].ToString();
                        //横向居中
                        range.HorizontalAlignment = XlVAlign.xlVAlignCenter;
                        range.EntireColumn.AutoFit();
                        range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThin, XlColorIndex.xlColorIndexAutomatic, System.Drawing.Color.Black.ToArgb());     //给单元格加边框

range = (Range)Activesheet.get_Range(string.Format("P{0}", nstart), string.Format("Q{0}", nstart));
                        range.Merge(0);
                        range.Value = dt.Rows[r][5].ToString();
                        //横向居中
                        range.HorizontalAlignment = XlVAlign.xlVAlignCenter;
                        range.EntireColumn.AutoFit();
                        range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThin, XlColorIndex.xlColorIndexAutomatic, System.Drawing.Color.Black.ToArgb());     //给单元格加边框

range = (Range)Activesheet.get_Range(string.Format("R{0}", nstart), string.Format("S{0}", nstart));
                        range.Merge(0);
                        range.Value = dt.Rows[r][6].ToString();
                        //横向居中
                        range.HorizontalAlignment = XlVAlign.xlVAlignCenter;
                        range.EntireColumn.AutoFit();
                        range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThin, XlColorIndex.xlColorIndexAutomatic, System.Drawing.Color.Black.ToArgb());     //给单元格加边框

range = (Range)Activesheet.get_Range(string.Format("T{0}", nstart));
                        range.Merge(0);
                        range.Value = dt.Rows[r][7].ToString();
                        //横向居中
                        range.HorizontalAlignment = XlVAlign.xlVAlignCenter;
                        range.EntireColumn.AutoFit();
                        range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThin, XlColorIndex.xlColorIndexAutomatic, System.Drawing.Color.Black.ToArgb());     //给单元格加边框

}

}

}
            //将第一个Sheet页设置为活动Sheet
            ((Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1]).Activate();

//xlApp.Visible = true;
            workbook.SaveAs(strFilePath);

//释放资源
            workbook.Close();
            xlApp.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
                
            System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);

//调用GC的垃圾收集方法(必须)
            GC.Collect();
            GC.WaitForPendingFinalizers();

}

时间: 2024-10-10 06:57:09

使用Office组件导出Excel表格的相关文章

office组件导出excel问题

传统企业的项目开发,采用技术都还比较陈旧,项目中涉及excel部分,采用office组件导出excel,进程采用强杀方式,涉及web服务器权限部分整合如下,均来自博客园. .NET导出Excel遇到的80070005错误的解决方法:   原文出处检索 COM 类工厂中 CLSID 为 {00024500-0000-0000-C000-000000000046}的组件时失败,原因是出现以下错误: 80070005基本上.net导出excel文件,都需要如此配置一下,不配置有的时候没错,而配置后基本

Element-ui组件库upload导出Excel表格

Element-ui组件库upload导出Excel表格 // 上传excel upload() { this.$refs.upload.submit(); //调用upload中自定义的方法 }, // 导入excel学生列表 uploadFile(item) { //:http-request自定义方法 const form = new FormData(); form.append("token", this.token); form.append("file"

Element-ui组件库Table表格导出Excel表格--存在重复数据问题

借鉴:https://www.jianshu.com/p/1971fc5b97ca https://blog.csdn.net/qq_40614207/article/details/94003793 贴出代码 // 定义导出Excel表格事件 exportExcel() { // 解决生成重复数据-因为使用l fixed属性 var fix = document.querySelector('.el-table__fixed') var wb // 判断要导出的节点中是否有fixed的表格,如

PHP导入导出excel表格图片(转)

写excel的时候,我用过pear的库,也用过pack压包的头,同样那些利用smarty等作的简单替换xml的也用过,csv的就更不用谈了.呵呵.(COM方式不讲了,这种可读的太多了,我也写过利用wps等进行word等的生成之类的文章 )但是在读的时候,只用过一种,具体是什么忘了,要回去翻代码了.基本上导出的文件分为两种:1:类Excel格式,这个其实不是传统意义上的Excel文件,只是因为Excel的兼容能力强,能够正确打开而已.修改这种文件后再保存,通常会提示你是否要转换成Excel文件.优

VB.NET版机房收费系统---导出Excel表格

datagridview,翻译成中文的意思是数据表格显示,使用DataGridView控件,可以显示和编辑来自不同类型的数据源的表格,将数据绑定到DataGridView控件非常简单和直观,大多数情况下,只需要设置DataSource属性即可,在绑定到包含多个列表或表的数据库源时,只需将DataMember属性设置为绑定的列表或表的字符串即可.机房收费系统多次用到数据表格的显示,并且导出为Excel表格,第一次机房收费系统是用VB版本的,她导出Excel的方法如下: 打开VB-工程-应用-勾选M

NPOI_winfrom导出Excel表格(合并单元格、规定范围加外边框、存储路径弹框选择)

1.导出 1 private void btn_print_Click(object sender, EventArgs e) 2 { 3 DataTable dtNew = new DataTable(); 4 5 dtNew.Columns.Add(new DataColumn("commodity_name", typeof(object))); 6 dtNew.Columns.Add(new DataColumn("specifications", type

.NET通过调用Office组件导出Word文档

.NET通过调用Office组件导出Word文档 最近做项目需要实现一个客户端下载word表格的功能,该功能是用户点击"下载表格",服务端将该用户的数据查询出来并生成数据到Word模板中,再反馈给客户端下载. 实现思路如下: 利用微软提供的Office的组件来完成,在服务器端指定目录放置一个word模板(该模板中需要替换的数据信息用书签标记好),当请求过来的时候,读取模板信息并将书签内容替换成从数据库获得的信息在返回给客户端下载即可,代码如下: #region 根据申请单ID号和模板生

c# Datagridview控件导入/导出excel表格

在写商业软件的时候,我们会经常遇到对excel表格的操控,最常见的就是Datagridview控件导入/导出excel表格.我也同样遇到了.运用了自己的知识,再加上网上的[大部分]都过期的源码,自己写出了这两个方法,当然,和绑定数据库一样,都用到了databel类. 导入: //private string fileName; /// <summary> /// 将DataGridView中数据导入到Excel /// </summary> /// <param name=&

原生JavaScript 导出excel表格(兼容ie和其他主流浏览器)

因同事的需求是想前端导出excel表格,网上找了一些demo,自己修改了一下,可能以后会用到,记录下来吧,兼容ie和一些主流浏览器,ie可能会报错,原因参考 这里,edge 浏览器还没有办法导出,正在尝试... <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>table 导出excel表格</title>