利用OpenXML SDK2.0 导出PPT的功能

本文档介绍了如何利用OpenXML SDK 2.0来创建和导出PowerPoint文件。通过SDK提供的工具,可以将PowerPoint文档转换为对应的C#代码,实现PPT的生成。示例代码包括按钮事件触发的PPT生成方法,PPT下载功能,以及用于辅助操作的PPTHelper类。
摘要由CSDN通过智能技术生成

相关软件包下载:http://www.microsoft.com/en-us/download/details.aspx?id=5124 

一个是SDK、一个是SDK Tool 

 

SDK Tool 内含API,也可以根据PPT(2007及以上版本)文档,生成对应的C#代码。 

 

生成文档的过程基本是:相应的类对应文档xml标签,各标签相互嵌套。

 

============================================================================

 

以下是项目用到的生成PPT并提供下载的实例代码:

1、按钮事件

        protected void btnExportPPT_Click(object sender, EventArgs e)
        {
            string fileName = Guid.NewGuid().ToString();
            string filePath = HttpContext.Current.Server.MapPath(@"/Document/" + fileName + ".pptx");
            string newFileName = string.Format("战略焦点{0}月份月报_{1}.pptx", BLL.FTS.AppWebContext.GetDOAMMonth(), DateTime.Now.ToString("yyyyMMddHHmm"));
            //生成PPT
            CreatePPT(filePath);
            //导出PPT
            OutputFile(filePath, newFileName);

        }


2、生成PPT方法

        /// <summary>
        /// 生成PPT文件
        /// </summary>
        /// <param name="fileName">生成PPT文件名称</param>
        private void CreatePPT(string filePath)
        {
            //

            System.IO.File.Copy(TempFilePath, filePath, true); //拷贝模版文件,供编辑 
            using (PresentationDocument pptDoc = PresentationDocument.Open(filePath, true))
            {
                int year = BLL.FTS.AppWebContext.GetDoamYear();
                int month = BLL.FTS.AppWebContext.GetDOAMMonth();
                bool isSdn = false;

                //Dn进展
                DataSet ds = new BLL.FTS.Criterion().GetDoamList(year, month,GetFilter());
                isSdn = false;
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    InsertSlide(pptDoc, isSdn, ds.Tables[0]);
                }


                //dn进展
                DataSet dsSdn = new BLL.SDN.Criterion().GetSdnDOAMListAndTag(year, month, GetFilter());
                isSdn = true;
                if (dsSdn != null && dsSdn.Tables.Count > 0 && dsSdn.Tables[0].Rows.Count > 0)
                {
                    InsertSlide(pptDoc, isSdn, dsSdn.Tables[0]);
                }

                firstTitleNum = 1;
                indexNum = 0;

                if (ds.Tables[0].Rows.Count < 1 && dsSdn.Tables[0].Rows.Count < 1)
                {
                    Kit.Alert("本月尚未录入进展!");
                }
            }
        }

        /// <summary>
        /// 根据数据源DataTabel和数据类型isSdn,向PPT文档插入幻灯片
        /// </summary>
        /// <param name="pptDoc"></param>
        /// <param name="isSdn"></param>
        /// <param name="dataTable"></param>
        private void InsertSlide(PresentationDocument pptDoc, bool isSdn, DataTable dataTable)
        {
            string[] firstTitleTemp = new string[3];


            //灯色
            int[] lightStatuId = { 4, 6, 3 };
            string[] lightStatuText = { "红", "橙", "黄" };

            string strFocusNo = string.Empty;
            string strTargetNo = string.Empty;

            //一级标题
            string[] firstTitle = new string[3];


            for (int i = 0; i < lightStatuId.Length; i++)
            {
                string strDnCodes = string.Empty;
                string strDnCode = string.Empty;
                bool needFirstTitle = true;

                //获得某灯色编号下的doam信息
                DataRow[] dataRows = dataTable.Select("EvolveStatusID ='" + lightStatuId[i] + "'");

                if (dataRows.Count() > 0)
                {
                    if (!isSdn)
                    {
                        firstTitleTemp[0] = "集团战略焦点(Dn)有";
                        firstTitleTemp[1] = "{0}个{1}灯项";
                        firstTitleTemp[2] = "(M)";
                    }
                    else
                    {
                        firstTitleTemp[0] = "集团公司重点工作计划的";
                        firstTitleTemp[1] = "{0}个{1}灯项";
                        firstTitleTemp[2] = "(m)";
                    }
                    //获取一级标题
                    firstTitleTemp[0] = string.Format("({0})", Common.PPTHelper.GetStrByInt32(firstTitleNum)) +
                                        firstTitleTemp[0];
                    firstTitleTemp[1] = string.Format(firstTitleTemp[1], dataRows.Count(), lightStatuText[i]);

                    firstTitle = firstTitleTemp;
                    //一级标题编号自增
                    firstTitleNum++;
                    foreach (DataRow dr in dataRows)
                    {
                        strFocusNo = dr["FocusNo"].ToString();
                        strTargetNo = dr["TargetNo"].ToString();
                        strDnCode = string.Format("{0}-{1}", strFocusNo, strTargetNo);
                        if (!strDnCodes.Contains(strDnCode))
                        {
                            //获得一个O下的M集合
                            DataRow[] drs =
                               dataRows.CopyToDataTable().Select("FocusNo='" + strFocusNo + "' and TargetNo='" + strTargetNo + "'", " a_SortWeight asc,c_SortWeight asc");

                            //M个数大于2时,要另起一页插入幻灯片
                            Common.PPTHelper.InsertNewSlide(pptDoc, ref indexNum, firstTitle, drs.ToList(), isSdn, needFirstTitle);

                            needFirstTitle = false;
                            strDnCodes += strDnCode + ",";
                        }
                    }
                }
            }
        }


3、下载PPT文档

        private void OutputFile(string filePath, string newFileName)
        {
            FileInfo fileInfo = new FileInfo(filePath);
            if (fileInfo.Exists)
            {
                using (FileStream fs = new FileStream(filePath, FileMode.Open))
                {

                    byte[] bytes = new byte[(int)fs.Length];
                    fs.Read(bytes, 0, bytes.Length);
                    fs.Close();
                    Response.ContentType = "application/octet-stream"; //通知浏览器载文件打        
                    Response.AddHeader("Content-Disposition",
                                       "attachment;  filename=" +
                                       HttpUtility.UrlEncode(newFileName, System.Text.Encoding.UTF8));

                    Response.Clear();
                    Response.BinaryWrite(bytes);
                    Response.Flush();

                }
                System.IO.File.Delete(filePath);

                Response.End();
            }
            else
            {
                Kit.Alert("导出失败,文件不存在!");
            }
        }

 

4、PPTHelper类

 public class PPTHelper
    {

        
        /// <summary>
        /// 将数字1-9转化为汉字
        /// </summary>
        /// <param name="num">范围1-9</param>
        /// <returns></returns>
        public static string GetStrByInt32(int num)
        {
            string strResult = string.Empty;

            switch (num)
            {
                case 1:
                    strResult = "一"; break;
                case 2:
                    strResult = "二"; break;
                case 3:
                    strResult = "三"; break;
                case 4:
                    strResult = "四"; break;
                case 5:
                    strResult = "五"; break;
                case 6:
                    strResult = "六"; break;
                case 7:
                    strResult = "七"; break;
                case 8:
                    strResult = "八"; break;
                case 9:
                    strResult = "九"; break;
                 default:
                    strResult = ""; break; 
            }

            return strResult;
        }

        
        // Insert the specified slide into the presentation at the specified position.
        /// <summary>
        /// 根据给出的O数据插入幻灯片
        /// </summary>
        /// <param name="presentationDocument">目标文档</param>
        /// <param name="indexNum">幻灯片插入位置</param>
        /// <param name="slideTitle">一级标题</param>
        /// <param name="drs">数据源</param>
        /// <param name="isSdn">是否是小dn</param>
        /// <param name="needFirstTitle">是否需要一级标题</param>
        public static void InsertNewSlide(PresentationDocument presentationDocument,ref int indexNum, string[] slideTitle,List<DataRow> drs,bool isSdn,bool needFirstTitle)
        {
            int position = indexNum;

            if (presentationDocument == null)
            {
                throw new ArgumentNullException("presentationDocument");
            }

            if (slideTitle == null)
            {
                throw new ArgumentNullException("slideTitle");
            }

            PresentationPart presentationPart = presentationDocument.PresentationPart;

            // Verify that the presentation is not empty.
            if (presentationPart == null)
            {
                throw new InvalidOperationException("The presentation document is empty.");
            }

            // Create the slide part for the new slide.为新幻灯片创建幻灯片部件。
            SlidePart slidePart = presentationPart.AddNewPart<SlidePart>();
            GenerateSlidePart1Content(slidePart, slideTitle, drs, presentationDocument,isSdn,needFirstTitle, position,ref indexNum);


            
        }

        /// <summary>
        /// 估算文本换行情况,估算所占高度
        /// </summary>
        /// <param name="width">编辑区域宽度px</param>
        /// <param name="str">文本</param>
        /// <param name="fontSize">字体大小px</param>
        /// <param name="lineHeight">行缝隙px</param>
        /// <returns></returns>
        private static int GetHeightByStr(int width, int fontSize, int lineHeight,params string[] str)
        {
            int result = 0;
            int length = 0;
            foreach (string s in str)
            {
                length += s.Length;
            }
            length -= 3;
            int lineCount = (((length * fontSize) / width) + ((length * fontSize) % width == 0 ? 0 : 1));
            result =lineCount* (fontSize +(lineCount>4? lineHeight/2:lineHeight));
            return result;
        }
       
       /// <summary>
       /// 过滤掉O或者M内容中的编号冒号
       /// </summary>
       /// <param name="str"></param>
       /// <returns></returns>
        public static string SubstringDoamNo(string str)
        {
            string result = str;
            int cutIndex = 0;
            if (str.Length >= 7)
            {
                cutIndex = str.Substring(0, 7).IndexOf(':'); //最长的情况——‘O12.11:’
            }
            else
            {
                cutIndex = str.IndexOf(':');
            }


           if (cutIndex<0)
           {
               if (str.Length >= 7)
               {
                   cutIndex = str.Substring(0, 7).IndexOf(':'); //最长的情况——‘O12.11:’
               }
               else
               {
                   cutIndex = str.IndexOf(':');
               }
           }
            if(cutIndex>0)
            {
                result = str.Substring(cutIndex+1);
            }

            return result;
        }
        
       // Generates content of slidePart1.
        private static void GenerateSlidePart1Content(SlidePart slidePart, string[] firstTitle, List<DataRow> drs, PresentationDocument presentationDocument,bool isSdn,bool needFirstTitle,int position, ref int indexNum)
        {
            long pxWidth = 12700L;//每个像素占用的宽度
            long basePointX = 457000L;//编辑区域原点X坐标
            long basePointY = 764000L;//编辑区域原点Y坐标

            long pointY = basePointY;

            int slideHeight = 480;//幻灯片可用高度px
            int slideWidth = 650;//幻灯片可用宽度px
            int lineHeight = 15;//行缝隙

            long cx = pxWidth*slideWidth;//幻灯片宽度

            #region slide
            Slide slide = new Slide();
            slide.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main");
            slide.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
            slide.AddNamespaceDeclaration("p", "http://schemas.openxmlformats.org/presentationml/2006/main");

            #region commonSlideDate
            CommonSlideData commonSlideData = new CommonSlideData();


            #region shapeTree
            ShapeTree shapeTree = new ShapeTree();

            NonVisualGroupShapeProperties nonVisualGroupShapeProperties = CreateNonVisualGroupShapeProperties("");

            GroupShapeProperties groupShapeProperties = CreateGroupShapeProperties();


            shapeTree.Append(nonVisualGroupShapeProperties);
            shapeTree.Append(groupShapeProperties);
            
            if (needFirstTitle)
            {
                #region shapeTitle一级菜单

                int titleFontSize = 2400;

                Shape shapeTitle = new Shape();

                NonVisualShapeProperties nonVisualShapeProperties = CreateNonVisualShapeProperties("标题1",
                                                                                                   PlaceholderValues.
                                                                                                       Title);

                long cy1 = GetHeightByStr(slideWidth, titleFontSize / 100, lineHeight, firstTitle) * pxWidth;
                ShapeProperties shapeProperties = CreateShapeProperties(basePointX, pointY, cx, cy1);

                pointY += cy1;

                #region textBody

                TextBody textBody = new TextBody();
                Drawing.BodyProperties bodyProperties = new Drawing.BodyProperties();
                Drawing.ListStyle listStyle = new Drawing.ListStyle();

                #region 添加一级菜单文本以及格式(a:p)
                //Drawing.Run[] runs = new Drawing.Run()[firstTitle.Count()];
                List<Drawing.Run> runList= new List<Run>();
                string colorValue = string.Empty;
                TextUnderlineValues textUnderlineValues = TextUnderlineValues.Single;
                foreach (string titlePart in firstTitle)
                {
                    
                    if(titlePart.IndexOf("红灯")>0)
                    {
                        colorValue = "FF0000";
                        textUnderlineValues = TextUnderlineValues.Single;
                    }
                    else if (titlePart.IndexOf("橙灯") > 0)
                    {
                        colorValue = "FF8E25";
                        textUnderlineValues = TextUnderlineValues.Single;
                    }
                    else if (titlePart.IndexOf("黄灯") > 0)
                    {
                        colorValue = "FFEF43";
                        textUnderlineValues = TextUnderlineValues.Single;
                    }
                    else
                    {
                        colorValue = null;
                        textUnderlineValues = TextUnderlineValues.None;
                    }
                    runList.Add(CreateRun(titlePart, "zh-CN", "en-US", titleFontSize, colorValue, null, true,
                                                       false, textUnderlineValues));
                }
                

                Drawing.EndParagraphRunProperties endParagraphRunProperties1 = new Drawing.EndPa
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值