C#导出word或者pdf方法----适用于word排版可能随时会变化的情况

实现步骤:

  1、从数据库取出要导出到word上的数据,用C#操作生成一个数据XMl文件,例如:a.xml

<?xml version="1.0" encoding="gb2312"?>
<History>
  <Customer>
    <CustomerName>1111      </CustomerName>
    <CustomerAddress>345345345</CustomerAddress>
    <CustomerTel>453453453435</CustomerTel>
    <CustomerContact>345</CustomerContact>
  </Customer>
  <StrOutTemplates>
    <StrOutTemplate ID="e36a279a-61da-4091-b6f2-2a780397f132">   3   </StrOutTemplate>
  </StrOutTemplates>
  <StrEquipments>
    <StrEquipment ID="34348dac-2400-4457-8b9e-cb9a5e432ad7">   equipment1   </StrEquipment>
  </StrEquipments>
  <StrReagents>
    <StrReagent ID="e6ac1aa0-c0df-46a1-8f30-abddc9200cc9">   试剂1(0.1V)   </StrReagent>
  </StrReagents>
  <StrConsumables>
    <StrConsumable ID="6ae5a792-874f-420a-9df2-83a0c3662a5f">   SDFAS(0.1O)   </StrConsumable>
  </StrConsumables>
  <SampleList>
    <SampleInfo>
      <Number ID="8b623852-d97b-4175-b861-8e58814b554c">YP00004</Number>
      <Name>222</Name>
      <Total>232</Total>
      <Quantity>3</Quantity>
      <Remain>229</Remain>
      <SampleCategoryNmae>category2</SampleCategoryNmae>
      <ValidDate>2012-12-04</ValidDate>
      <SavedCondition>2323</SavedCondition>
      <SavedPlace>2323232323</SavedPlace>
    </SampleInfo>
  </SampleList>
  <Environment>1312321</Environment>
  <Memo>32424234</Memo>
  <ProjectRecord><![CDATA[<p>34234243242342342</p><p><img id="imagediv" src="/UploadAttatchment/Record/2012/12/01/1be149d4-d434-49ad-861d-18423d2b0c13/201212011229129728_$Thumbnail$Koala - 副本.jpg" alt="" data-mce-src="/UploadAttatchment/Record/2012/12/01/1be149d4-d434-49ad-861d-18423d2b0c13/201212011229129728_$Thumbnail$Koala - 副本.jpg"></p> ]]></ProjectRecord>
  <Result><![CDATA[<p>32424234234</p>]]></Result>
</History>
View Code

 2、用xsl文件创建一个xml数据的显示模板,模板中的html标签根据要导出的word排版,并且和xml的节点匹配,可以设置样式。如:b.xsl

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:template match="History">
    <dl class="noborder">
      <dt style="float:right;">
        <em>实验人:</em>
        <xsl:value-of select='ExperimentName'/>
      </dt>
      <dt>检测信息</dt>
      <dd>
        <ul>
          <li>
            <em>客户名称:</em>
            <xsl:value-of select='Customer/CustomerName'/>
          </li>
          <li>
            <em>客户地址:</em>
            <xsl:value-of select='Customer/CustomerAddress'/>
          </li>
          <li>
            <em>联系电话:</em>
            <xsl:value-of select='Customer/CustomerTel'/>
          </li>
          <li>
            <em>联系人:</em>
            <xsl:value-of select='Customer/CustomerContact'/>
          </li>
          <li>
            <em>检测依据:</em>
            <xsl:apply-templates select='StrOutTemplates'/>
          </li>
          <li>
            <em>主要仪器:</em>
            <xsl:apply-templates select='StrEquipments'/>
          </li>
          <li>
            <em>使用试剂:</em>
            <xsl:apply-templates select='StrReagents'/>
          </li>
          <li>
            <em>使用耗材:</em>
            <xsl:apply-templates select='StrConsumables'/>
          </li>
          <li>
            <em>实验环境:</em>
            <xsl:value-of select='Environment'/>
          </li>
          <li>
            <em>备注:</em>
            <xsl:value-of select='Memo'/>
          </li>
        </ul>
      </dd>
    </dl>
    <dl class="noborder">
      <dt>检测项目实验记录</dt>
      <dd>
        <xsl:value-of select='ProjectRecord' disable-output-escaping="yes"/>
      </dd>
    </dl>
    <dl class="noborder">
      <dt>结论</dt>
      <dd>
        <xsl:value-of select='Result' disable-output-escaping="yes"/>
      </dd>
    </dl>
    <dl class="noborder">
      <dt>样品信息</dt>
      <dd>
        <div class="z-sample-msg">
          <TABLE>
            <TR >
              <TD Width="75">样品编号</TD>
              <TD Width="140">样品名称</TD>
              <TD Width="75">样品量</TD>
              <TD Width="75">本次用量</TD>
              <TD Width="75">样品余量</TD>
              <TD Width="100">样品类别</TD>
              <TD Width="115">有效期至</TD>
              <TD Width="100">存放条件</TD>
              <TD Width="100">存放地点</TD>
            </TR>
            <xsl:apply-templates select='SampleList'/>
          </TABLE>


        </div>
      </dd>
    </dl>
  </xsl:template>
  <xsl:template match="StrOutTemplates">

    <xsl:apply-templates select='StrOutTemplate'/>
   

  </xsl:template>

  <xsl:template match="StrEquipments">

    <xsl:apply-templates select='StrEquipment'/>

  </xsl:template>

  <xsl:template match="StrReagents">

    <xsl:apply-templates select='StrReagent'/>

  </xsl:template>
  <xsl:template match="StrConsumables">

    <xsl:apply-templates select='StrConsumable'/>

  </xsl:template>

  <xsl:template match="SampleInfo">
    <TR style="background-color:white">
      <TD>
        <xsl:value-of select='Number'/>
      </TD>
      <TD>
        <xsl:value-of select='Name'/>
      </TD>
      <TD>
        <xsl:value-of select='Total'/>
      </TD>
      <TD>
        <xsl:value-of select='Quantity'/>
      </TD>
      <TD>
        <xsl:value-of select='Remain'/>
      </TD>
      <TD>
        <xsl:value-of select='SampleCategoryNmae'/>
      </TD>
      <TD>
        <xsl:value-of select='ValidDate'/>
      </TD>
      <TD>
        <xsl:value-of select='SavedCondition'/>
      </TD>
      <TD>
        <xsl:value-of select='SavedPlace'/>
      </TD>
    </TR>
  </xsl:template>
</xsl:stylesheet>
View Code

3.再根据C#操作类将a.xml按照b.xsl格式生成c.html,操作类如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aspose.Words;
using System.IO;
using System.Xml.Xsl;
using System.Xml;
using System.Diagnostics;
using System.Web;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.DataVisualization.Charting;


namespace Util
{
    public class DocBuild
    {
        private static string XsltToHtml(string xmlDataFile, string xsltTemplateFile, string output_html_file)
        {
            XslCompiledTransform trans = new XslCompiledTransform();
            try
            {
                trans.Load(xsltTemplateFile);
                trans.Transform(xmlDataFile, output_html_file);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            finally
            {
                trans = null;
                GC.Collect();
            }

            return string.Empty;
        }

        public static string HtmlToWord(string htmlOutput, string wordOutputFile)
        {
            var wordOutputPath = Path.GetFullPath(wordOutputFile);
            wordOutputPath = wordOutputPath.Substring(0, wordOutputPath.LastIndexOf("\\"));
            if (!Directory.Exists(wordOutputPath))
                Directory.CreateDirectory(wordOutputPath);

            Document htmlDoc = null;
            try
            {
                htmlDoc = new Document(htmlOutput);
                htmlDoc.Save(wordOutputFile, Aspose.Words.SaveFormat.Doc);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            finally
            {
                htmlDoc = null;
                GC.Collect();
            }

            return string.Empty;
        }

        public static string InsertTableOfContents(string wordOutputFile)
        {
            try
            {
                Document doc = new Document(wordOutputFile);
                DocumentBuilder builder = new DocumentBuilder(doc);
                builder.MoveToBookmark("InsertTableOfContents");
                // Insert a table of contents at the beginning of the document.
                builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");

                // The newly inserted table of contents will be initially empty.
                // It needs to be populated by updating the fields in the document.
                doc.UpdateFields();

                doc.Save(wordOutputFile, Aspose.Words.SaveFormat.Doc);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            finally
            {
                GC.Collect();
            }

            return string.Empty;
        }

        public static string XsltToWord(string xmlDataFile, string xsltTemplateFile, string wordOutputFile, string tempDataDir)
        {
            var output_html_file = Path.Combine(tempDataDir, Guid.NewGuid() + ".temp.html");
            var codePath = Path.Combine(tempDataDir, "qrcode");

            var res = string.Empty;
            res = DocBuild.XsltToHtml(xmlDataFile, xsltTemplateFile, output_html_file);
            if (!string.IsNullOrEmpty(res))
                return res;
            res = DocBuild.HtmlToWord(output_html_file, wordOutputFile);
            if (!string.IsNullOrEmpty(res))
                return res;
            res = DocBuild.InsertTableOfContents(wordOutputFile);
            if (!string.IsNullOrEmpty(res))
                return res;

            try
            {
                File.Delete(output_html_file);
                Directory.Delete(codePath, true);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

            return string.Empty;
        }

        public static string WordToPdf(string wordOutputFile)
        {
            string pdfOutputFile = string.Concat(wordOutputFile.Substring(0, wordOutputFile.LastIndexOf(".")), ".pdf");

            var res = string.Empty;

            try
            {
                Document doc = new Document(wordOutputFile);

                doc.Save(pdfOutputFile, SaveFormat.Pdf);
            }
            catch (Exception ex)
            {
                res = ex.Message;
            }
            finally
            {
                GC.Collect();
            } 

            return res;
        }

        /// <summary>
        /// 读取html文件为字符串
        /// </summary>
        /// <param name="HtmlPath"></param>
        /// <returns></returns>
        public static string HtmlFileToString(string HtmlPath)
        {
            string HtmlString = string.Empty;
            using (System.IO.StreamReader sr = new System.IO.StreamReader(HtmlPath))
            {
                HtmlString = sr.ReadToEnd();
            }
            try
            {
                System.IO.File.Delete(HtmlPath);
            }
            catch
            {
            }
            return HtmlString;
        }



    }
}
View Code

在外部调用此类中的方法就可以直接生成word和pdf了

posted @ 2013-06-09 14:36  yjwpop  阅读(769)  评论(0)    收藏  举报