C#下Excel的普通处理和报表设计

一、准备:想要操作Excel,先要在添加2个COM引用:

1、Microsoft Excel 14.0 Object Library (版本不同14.0也可能是12.0等)

2、Microsoft Office 14.0 Object Library 

二、操作:

在Winform中,也须添加引用

using Microsoft.Office.Interop.Excel;

 相应的,本类中原有的Datatable应改为System.Data.DataTable,否则将与Excel.Datatable冲突。

public partial class FrmExcelOp : Form
{
private Microsoft.Office.Interop.Excel.Application excel;  //定义一个变量供全局使用
object missing = System.Reflection.Missing.Value;    //定义一个参数变量供全局使用

}

        private void ExportIvoice()
        {
            #region 变量定义
            Workbook wkBookTmpInvoice = null;
            Workbook wkBookTag = null;
            #endregion

            try
            {
                 #region Excel准备阶段
                if (!Directory.Exists(tagTempFolder))
                {
                    Directory.CreateDirectory(tagTempFolder);
                }
                if (!Directory.Exists(tagFolder))
                {
                    Directory.CreateDirectory(tagFolder);
                }

                if (excel2 == null)
                {
            //创建实例
                    excel2 = new Microsoft.Office.Interop.Excel.Application
                    {
                        UserControl = true
                    };
                }

                if (excel2 == null)
                {
                    MyMsg.Stop("无法打开EXCEL,请检查系统配置.");
                    return;
                }

          //...其它操作
                wkBookTmp = excel2.Application.Workbooks.Open(tmpFileFullName, missing, true, missing, missing, missing, missing, missing, missing, true, missing, missing, missing, missing, missing); 
          //可写/可编辑打开一个工作薄;
                if (wkBookTmpInvoice == null)
                {                   
                    MyMsg.Exclamation("开启文件失败,请检查!");
                    return;
                }
                for (int i = 1; i <= wkBookTmp .Sheets.Count; i++)
                {
                    Worksheet tmpSht = wkBookTmp .Sheets[i];
                    //添加上边线
                    tmpSht.Range["A13", "L13"].Borders.Item[XlBordersIndex.xlEdgeTop].LineStyle = XlLineStyle.xlContinuous;
                    //去除部分信息(给单元格赋值)
                    if (i < wkBookTmp .Sheets.Count) tmpSht.Range["A23", "A26"].Value2 = string.Empty;
                }
          //新建一个工作簿,后面可以保存为文件
                wkBookTag = excel2.Workbooks.Add();
                if (wkBookTag != null)
                {
                    string tInvSheetName = "INV01";
                    //给工作簿中的表重命名
                    ((Worksheet)wkBookTmp .Sheets[1]).Name = tInvSheetName;
            //将工作簿的表1拷贝一份插入到另一个工作簿的表1的前面
                    ((Worksheet)wkBookTmp .Sheets[1]).Copy(wkBookTag.Sheets[1]);

                    Worksheet tagSheet = wkBookTag.Sheets[tInvSheetName];
                    tagSheet.PageSetup.Zoom = false;
                    tagSheet.PageSetup.FitToPagesTall = false;   //所有列调整为一页,与Excel的缩放设置对应,避免拆成2页打印
                    tagSheet.PageSetup.CenterHorizontally = true;//水平居中
                    tagSheet.PageSetup.PrintTitleRows = "$1:$12";//每页都打印的报表抬头
                    tagSheet.VPageBreaks.Add(tagSheet.Range["M1"]); //调整纵向分页符到最后一列

                    for (int r = 13; r < 23; r++)
                    {
                        tagSheet.Rows[r].RowHeight = 38; //调整明细数据行高度
                    }
                    //部分复制其它数据表
                    for (int i = 2; i <= wkBookTmp .Sheets.Count; i++)
                    {
                        int topPos = 28 + 13 * (i - 2);
                        int rightPos = 41 + 13 * (i - 2);
                        tagSheet.Range["A" + topPos].PageBreak = 1;//在某行上方插入横向分页符

            //删除默认的工作表
                    wkBookTag.Sheets["Sheet1"].Delete();
                    wkBookTag.Sheets["Sheet2"].Delete();
                    wkBookTag.Sheets["Sheet3"].Delete();
                }
                #endregion



         //............
                

                //以16行为复制行,在后面批量插入15行(相当于在Excel中复制16行,再选中17后面的15行,再右键-》插入复制的行)
                tagSheetPL.Rows["17:32"].Insert(XlDirection.xlDown, tagSheetPL.Rows["16"].Copy());

          //......

                #region 结尾清理及更新操作日志
                //保存并关闭完成所有操作的目标文件(xlOpenXMLWorkbook为.xlsx后缀,如果要.xls后缀,需要设置为xlOpenNormal
                wkBookTag.SaveAs(tagFileFullName, XlFileFormat.xlOpenXMLWorkbook);
                wkBookTag.Close(false);
                wkBookTag = null;
                //以下放在保存之后再关闭
                wkBookTmpInvoice.Close(false);//不保存关闭
                wkBookTmpInvoice = null;
                File.Delete(tmpInvoiceFullName);//删除临时文件
            }
            catch (Exception ex)
            {
                if (wkBookTag != null) wkBookTag.Close();
                if (wkBookTmpInvoice != null)
                {
                    wkBookTmpInvoice.Close(false);//不保存关闭
                    File.Delete(tmpInvoiceFullName);//删除临时文件
                }
            }
            finally
            {

            }
        }
View Code
                                //插入字符,指定字体
        if (!string.IsNullOrEmpty(MXRmk))
                                    {
                                        var objTextBox = wkSheet.Shapes.AddTextbox(Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationHorizontal,uleft,utop, 200, 32);
                                        objTextBox.Name = "TextBox1";   //这行必须的。它直接影响下一行。 
                                        //objTextBox.Fill.Visible = 0;
                                        objTextBox.Line.Weight = 3;
                                        objTextBox.Line.ForeColor.RGB = Color.Black.ToArgb();
                                        objTextBox.TextFrame2.TextRange.Characters.Text=""+ MXRmk +"";
                                        objTextBox.TextFrame2.TextRange.Characters.Font.Size = 22;
                                        objTextBox.TextFrame2.TextRange.Characters.Font.Bold = Microsoft.Office.Core.MsoTriState.msoCTrue;
                                    }
        
插入字符
                                            //指定位置为A2处
                                            float aleft = (float)partnoBarRange.Left+10;
                                            float atop = (float)partnoBarRange.Top;
                                            float aheight = (float)partnoBarRange.Height;

                                            wkSheet.Shapes.AddPicture(tmpFN, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, aleft, atop, 100, aheight-2);
插入二维码图片
                                    if (chkPreviewFirst.Checked)
                                    {
                                        excelPrint.Visible = true;
                                        wkSheet.PrintPreview(false);
                                    }
                                    else
                                    {
                                        excelPrint.Visible = false;
                                        wkSheet.PrintOutEx();
                                    }
打印预览与直接打印

 。。。

原文地址:https://www.cnblogs.com/imes/p/9732752.html