[置顶] ASP.NET2.0 生成Word 2007并下载方案

 

1.开发用途:用于将页面数据或者后台数据生成word2007格式,并提供下载。

2.开发环境:vs2008 + office2007 + DocumentFormat.OpenXml sdk(我用的版本是:2.0.4330.0,具体组件可在微软官方下载)。

3.主要代码如下:

 

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;


    /// <summary>
    /// 生成2007文档
    /// </summary>
    /// <param name="docName"></param>
    public void CreateDocumentFile(string docName)
    {
        // Create a Wordprocessing document. 
        string temp = Server.MapPath(@"..\Template\个人履历.docx");
        if (File.Exists(temp)) File.Delete(temp);
        File.Copy(docName, temp);
        using (WordprocessingDocument myDoc = WordprocessingDocument.Open(temp, true))
        {
            DocumentFormat.OpenXml.Wordprocessing.Table table = CreateMainTable(12, 4, true,myDoc);

            
            myDoc.MainDocumentPart.Document.Body.Append(table);


            myDoc.MainDocumentPart.Document.Save();
        }
        ResponseFile(temp);
    }

    /// <summary>
    /// 生成页面主表格
    /// </summary>
    /// <param name="rowCount"></param>
    /// <param name="ColumnCount"></param>
    /// <param name="HaveBorder"></param>
    /// <param name="wd"></param>
    /// <returns></returns>
    protected DocumentFormat.OpenXml.Wordprocessing.Table CreateMainTable(int rowCount, int ColumnCount, bool HaveBorder,WordprocessingDocument wd)
    {
        //创建新表格
        DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table();
        
        //设置表格边线
        DocumentFormat.OpenXml.Wordprocessing.TableProperties tblPr = TpHaveBorder(true);
        table.Append(tblPr);

        DocumentFormat.OpenXml.Wordprocessing.TableRow tr =new DocumentFormat.OpenXml.Wordprocessing.TableRow();
        DocumentFormat.OpenXml.Wordprocessing.TableCell tc=new DocumentFormat.OpenXml.Wordprocessing.TableCell();
        //first row - title

        //主要资料录入
        DocumentFormat.OpenXml.Wordprocessing.Table ta = CreateSubTable(1, 2,wd);
        tc.Append(ta);

        //
        TableCellProperties tcp = new TableCellProperties();
        GridSpan gridSpan = new GridSpan();
        gridSpan.Val = 11;
        tcp.Append(gridSpan);
        tc.Append(tcp);

        DocumentFormat.OpenXml.Wordprocessing.Text x = new DocumentFormat.OpenXml.Wordprocessing.Text("");

        Run run_paragraph = new Run();
        run_paragraph.Append(x);
        DocumentFormat.OpenXml.Wordprocessing.Paragraph paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
        paragraph.Append(run_paragraph);


        tc.Append(paragraph); tr.Append(tc); table.Append(tr);
        IList<LINQDB.HRDB.EmpFile_Education> edu;
        IList<LINQDB.HRDB.EmpFile_Family> fam;
        IList<LINQDB.HRDB.EmpFile_Working> work;
        IList<LINQDB.HRDB.EmpFile_Emergency> emer;
        using (var db = new LINQDB.HRDB.HRDBDataContext())
        {
            fam = db.EmpFile_Family.Where(p => p.EmpID == PageArg.Id1).ToList();

            edu = db.EmpFile_Education.Where(p => p.EmpID == PageArg.Id1).ToList();

            emer = db.EmpFile_Emergency.Where(p => p.EmpID == PageArg.Id1).ToList();

            work = db.EmpFile_Working.Where(p => p.EmpID == PageArg.Id1).ToList();
        }
        table = CreateFamilyDoc(table, fam); table = CreateEduDoc(table, edu); table = CreateEmerDoc(table,emer);
        table = CreateWorkDoc(table, work);
        return table;
    }

    /// <summary>
    /// 创建子表格
    /// </summary>
    /// <param name="rowCount"></param>
    /// <param name="ColumnCount"></param>
    /// <returns></returns>
    protected DocumentFormat.OpenXml.Wordprocessing.Table CreateSubTable(int rowCount, int ColumnCount,WordprocessingDocument wd)
    {
        string imageId = "rIdImg";string picName = PageArg.Id1+".jpg";string fullPath = RootPath + @"\Employees\"+picName;
        if (!File.Exists(fullPath))
        {
            fullPath = GetDefaultPhotoPath(RootPath);
            picName = fullPath.Substring(fullPath.LastIndexOf(@"\")+1);
        }
        ImagePart imagePart = wd.MainDocumentPart.AddImagePart(ImagePartType.Jpeg, imageId);
        using (FileStream stream = new FileStream(fullPath, FileMode.Open))
        {
            imagePart.FeedData(stream);
        }
         

        DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table();

        DocumentFormat.OpenXml.Wordprocessing.TableProperties tblPr = TpHaveBorder(false);table.Append(tblPr);

        DocumentFormat.OpenXml.Wordprocessing.TableRow tr = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
        DocumentFormat.OpenXml.Wordprocessing.TableCell tc = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
        DocumentFormat.OpenXml.Wordprocessing.Paragraph paragraph = CreateCellText("个人履历");
        tc.Append(paragraph);
        tr.Append(tc); table.Append(tr);
        int k = -1;

        for (int i = 0; i < 5; i++)
        {
            tr = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
            for (int j = 0; j < 4; j++)
            {
                k++;
                tc = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
                if (j == 0)
                {
                    if( k > 0)
                    k--;
                    TableCellProperties tp;
                    if (i == 0)
                    {
                        tp = new TableCellProperties(
                            new TableCellWidth() { Width = 2093, Type = TableWidthUnitValues.Dxa },
                                        new VerticalMerge() { Val = MergedCellValues.Restart });
                    }
                    else
                    {
                        tp = new TableCellProperties(
                            new TableCellWidth() { Width = 2093, Type = TableWidthUnitValues.Dxa },
                                        new VerticalMerge() { Val = MergedCellValues.Continue });
                    }
                    if (i == 0)
                    {

                        Run rDrawing = new Run();
                        string img = CreateImageXml(imageId, picName, 1133334, 1371429);
                        Drawing d = new Drawing(img);
                        rDrawing.AppendChild(d);
                        DocumentFormat.OpenXml.Wordprocessing.Paragraph pDrawing = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
                        pDrawing.AppendChild(rDrawing);
                        tc.AppendChild(pDrawing);
                        
                    }
                    tc.Append(tp);
                }
                if (i == 0 && j == 0) { }
                else
                tc.Append(CreateCellText(showName[k]));
                tr.Append(tc);
            }
            table.Append(tr);

        }
        for (int i = 0; i < 2; i++)
        {
            tr = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
            
                k++;
                tc = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
                
                TableCellProperties tp = new TableCellProperties(
                        new TableCellWidth() { Type = TableWidthUnitValues.Dxa },
                                    new GridSpan() { Val = 4 });
                tc.Append(tp);
                tc.Append(CreateCellText(showName[k]));
                tr.Append(tc);
            table.Append(tr);
        }
        for (int i = 0; i < 3; i++)
        {
            tr = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
            for (int j = 0; j < 4; j++)
            {
                k++;
                tc = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
                tc.Append(CreateCellText(showName[k]));
                tr.Append(tc);
            }
            table.Append(tr);
        }
        return table;

    }
    
    /// <summary>
    /// 生成TableCell中图片
    /// </summary>
    /// <param name="relId">imagePart's Id</param>
    /// <param name="imageName">图片名称,不带路径</param>
    /// <param name="width">图片宽度</param>
    /// <param name="height">图片高度</param>
    /// <returns></returns>
    protected string CreateImageXml(string relId, string imageName, int width, int height)
    {
        //Looking to add an image to WordprocessingML? Creating the xml is the easiest way. 
        string img = @"
                <w:drawing xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"">
                    <wp:inline xmlns:wp=""http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"">
                      <wp:extent cx=""" + width + @""" cy=""" + height + @""" />
                      <wp:docPr name=""" + imageName + @""" id=""1"" />
                      <a:graphic xmlns:a=""http://schemas.openxmlformats.org/drawingml/2006/main"">
                        <a:graphicData uri=""http://schemas.openxmlformats.org/drawingml/2006/picture"">
                          <pic:pic xmlns:pic=""http://schemas.openxmlformats.org/drawingml/2006/picture"">
                            <pic:nvPicPr>
                              <pic:cNvPr id=""0"" name=""" + imageName + @""" />
                              <pic:cNvPicPr />
                            </pic:nvPicPr>
                            <pic:blipFill>
                              <a:blip r:embed=""" + relId + @""" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"" />
                              <a:stretch>
                                <a:fillRect />
                              </a:stretch>
                            </pic:blipFill>
                            <pic:spPr>
                              <a:xfrm>
                                <a:off x=""0"" y=""0"" />
                                <a:ext cx=""" + width + @""" cy=""" + height + @""" />
                              </a:xfrm>
                              <a:prstGeom prst=""rect"" />
                            </pic:spPr>
                          </pic:pic>
                        </a:graphicData>
                      </a:graphic>
                    </wp:inline>
                  </w:drawing>";

        return img;
    }

     /// <summary>
    /// 创建文本
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    protected DocumentFormat.OpenXml.Wordprocessing.Paragraph CreateCellText(string context)
    {
        DocumentFormat.OpenXml.Wordprocessing.Text x = new DocumentFormat.OpenXml.Wordprocessing.Text(context);

        Run run_paragraph = new Run(); run_paragraph.Append(x);
        
        DocumentFormat.OpenXml.Wordprocessing.Paragraph paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(); paragraph.Append(run_paragraph);
        
        return paragraph;
    }

    /// <summary>
    /// 表格属性
    /// </summary>
    /// <param name="isHave">是否具有框线</param>
    /// <returns></returns>
    protected TableProperties TpHaveBorder(bool haveBorder)
    {
        BorderValues bv = haveBorder == true ? BorderValues.Single : BorderValues.None;

        DocumentFormat.OpenXml.Wordprocessing.TableProperties tblPr = new DocumentFormat.OpenXml.Wordprocessing.TableProperties(); TableBorders tblBorders = new TableBorders();

        tblBorders.TopBorder = new DocumentFormat.OpenXml.Wordprocessing.TopBorder();
        tblBorders.TopBorder.Val = new EnumValue<BorderValues>(bv);
        tblBorders.BottomBorder = new DocumentFormat.OpenXml.Wordprocessing.BottomBorder();
        tblBorders.BottomBorder.Val = new EnumValue<BorderValues>(bv);
        tblBorders.LeftBorder = new DocumentFormat.OpenXml.Wordprocessing.LeftBorder();
        tblBorders.LeftBorder.Val = new EnumValue<BorderValues>(bv);
        tblBorders.RightBorder = new DocumentFormat.OpenXml.Wordprocessing.RightBorder();
        tblBorders.RightBorder.Val = new EnumValue<BorderValues>(bv);
        tblBorders.InsideHorizontalBorder = new DocumentFormat.OpenXml.Wordprocessing.InsideHorizontalBorder();
        tblBorders.InsideHorizontalBorder.Val = bv;
        tblBorders.InsideVerticalBorder = new DocumentFormat.OpenXml.Wordprocessing.InsideVerticalBorder();
        tblBorders.InsideVerticalBorder.Val = bv;
        tblPr.Append(tblBorders);

        return tblPr;

    }


总结:有关生成word2007的文章不少,可大部分都千篇一律,而且也没有什么实际意义.于是把眼光放到MSDN,终于,在总结两位外国编程高手的代码,并加以修改和融合后,形成了最终如上图所示的效果.基本算是合格了.当然代码写得不太好.有些乱.待有时间逐步完善和改进一下.希望此篇"杂文"中的一些代码段能对同行们有所帮助,也希望读者能有更简洁的生成word2007的方案,此文权当是抛砖引玉吧.

你可能感兴趣的:([置顶] ASP.NET2.0 生成Word 2007并下载方案)