使用Office组件导出Excel表格

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用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();

        }

以上是关于使用Office组件导出Excel表格的主要内容,如果未能解决你的问题,请参考以下文章

在winform中怎么导出WPS表格?

Office表中如何把一定范围单元格的内容多列数据去除空值以TXT文本方式导出?

Office Com组件根据模板导出Excel

C#导出excel 不安装office excel情况下

c# 只安装WPF环境 导出excel表格 问题

●导出excel(office组件)