现在的位置: 首页 > 综合 > 正文

C# 导入word word导入

2018年02月15日 ⁄ 综合 ⁄ 共 11327字 ⁄ 字号 评论关闭

/// </summary>
        /// <param name="objFileRelativePath">导入Word文件拷贝在服务器上的全路径</param>
        /// <param name="sScript">出错时的提示信息</param>
        /// <param name="listRptID">导入生成报告的ID数组</param>
        /// <param name="strXMLPath">用于数据验证的XML文件名</param>
        /// <param name="strButID">导入按钮ID</param>
        private void ImportWord(ref object objFileRelativePath, StringBuilder sScript, ref ArrayList listRptID,string strXMLPath,string strButID)
        {

            Microsoft.Office.Interop.Word.ApplicationClass wordApp = null;
            object Missing = Type.Missing;
            Microsoft.Office.Interop.Word.Document wordDoc = null;
            using (clsDbAccept db = new clsDbAccept())
            {
                try
                {
                    wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
                    wordDoc = wordApp.Documents.Open(ref objFileRelativePath, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
                         ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing);
                    //导入报告的创建者为当前用户
                    string strCreater = Session["UserID"] != null ? Session["UserID"].ToString() : string.Empty;

                    #region XML文件,用于校验上传Word中数据的正确性
                    strXMLPath = this.Server.MapPath(clsCommon.GetUrl(this, strXMLPath));
                    DataSet dsXML = ReadXMLFile(strXMLPath);
                    //所有报告信息构成的表
                    DataTable dtTable = null;
                    //单个具体报告构成的表
                    DataTable dtCol = null;
                    //特殊报告项验证信息构成的表
                    DataTable dtColCondition = null;
                    DataView dvTable = null;
                    DataView dvCol = null;
                   

                    if (dsXML != null && dsXML.Tables.Count > 1)
                    {
                        dtTable = dsXML.Tables[0];
                        dtCol = dsXML.Tables[1];
                        if (dsXML.Tables.Count > 2)
                        {
                            dtColCondition = dsXML.Tables[2];
                        }
                    }
                    if (dtTable != null && dtTable.Rows.Count > 0)
                    {
                        dvTable = dtTable.DefaultView;
                        dvTable.RowFilter = string.Format("[TableType]='{0}'", strButID);
                        dtTable = dvTable.ToTable();
                    }

                    //表格内容开始行
                    int IntStartRowIndex = Convert.ToInt32(dtTable.Rows[0]["StartRowIndex"].ToString());
                    //表格内容开始列
                    int IntStartColIndex = Convert.ToInt32(dtTable.Rows[0]["StartColIndex"].ToString());
                    string strTable_Id = dtTable.Rows[0]["Table_Id"].ToString();
                   

                    if (dtCol != null && dtCol.Rows.Count > 0)
                    {
                        dvCol = dtCol.DefaultView;
                        dvCol.RowFilter = string.Format("[Table_Id]='{0}'", strTable_Id);
                        dtCol = dvCol.ToTable();
                    }
                    int IntSentenceIndex = Convert.ToInt32(dtTable.Rows[0]["SentenceIndex"].ToString());
                    #endregion
                  
                    if (TYPE == "19")
                    {
                        switch (strButID)
                        {
                            //add by chairuirui 2013-3-6 start 元器件质量等级使用数量统计
                            case "execWord_19":
                                ExecWord_19(wordDoc, IntSentenceIndex, dtCol, dtColCondition, IntStartRowIndex, IntStartColIndex, strCreater, sScript, db, ref listRptID);
                                break;
                            //add by chairuirui 2013-3-6 end 元器件质量等级使用数量统计
                        }
                    }
                }
                catch
                {
                    //事务回滚
                    db.SetRollback();
                    sScript.Append("导入数据出现异常情况!");
                }

                finally
                {
                    if (sScript.Length > 0)
                    {
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "", sScript.ToString(), true);
                    }
                    wordDoc.Close(ref Missing, ref Missing, ref Missing);
                    wordApp.Quit(ref Missing, ref Missing, ref Missing);
                    wordDoc = null;
                    wordApp = null;
                    GC.Collect();
                }
            }
        }
        #endregion

       protected void ImportWord(object obj, EventArgs e)
        {
            //触发事件按钮ID
            string strButID = ((System.Web.UI.HtmlControls.HtmlInputControl)(obj)).Name;
            string strXMLPath = string.Empty;
            switch (NAVBAR_TYPE)
            {
                case "19":
                case "18":
                    strXMLPath = "WordImport.xml";
                    break;              
            }
            //导人模版绘画
            Page.ClientScript.RegisterStartupScript(this.GetType(), "模版下载绘画", ShowUploadBtn());

            if (ReportFile.PostedFile.ContentLength > 0)
            {
                //上传全路径
                string strUploadFileAllName = ReportFile.PostedFile.FileName;
                //上传文件名
                string strUploadFileName = strUploadFileAllName.Substring(strUploadFileAllName.LastIndexOf("\\") + 1);
                //上传文件类型
                string strFileType = strUploadFileName.Substring(strUploadFileName.LastIndexOf('.') + 1).ToLower();
                if (strFileType != "doc" && strFileType != "docx")
                {
                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "提示只能上传WORD文件", "alert('文件格式不对!请上传WORD文件。');", true);
                    return;
                }
                //服务器上保存上传Word副本,用于读取内容
                object objFileRelativePath = FileSave(".doc");

                //导入生成报告ID数组
                ArrayList listRptID = new ArrayList();
                //导入出错时的提示信息
                StringBuilder sScript = new StringBuilder();
                //读取Word文件内容并创建报告
                ImportWord(ref objFileRelativePath, sScript, ref listRptID, strXMLPath, strButID);
                if (sScript.Length > 0)
                {
                    for (int i = 0; i < listRptID.Count; i++)
                    {
                        string strRptID = listRptID[i].ToString();
                        IARREP.Del(db, strRptID);
                    }
                }
                else
                {
                    sScript.Append("导入成功。");
                }
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "提示信息", string.Format("alert('{0}');", sScript.ToString()), true);
            }
            else
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "提示选择导入文件", "alert('请选择导入文件!');", true);
            }
        }

/// <summary>
        /// 2013-3-7
        /// </summary>
        /// <param name="wordDoc">用于读取Word内容</param>
        /// <param name="IntSentenceIndex">用于读取非表格数据</param>
        /// <param name="dtCol">用于数据校验</param>
        /// <param name="dtColCondition">用于数据校验</param>
        /// <param name="IntStartRowIndex">表格内容开始行</param>
        /// <param name="IntStartColIndex">表格内容开始列</param>
        /// <param name="strCreater">报告创建者</param>
        /// <param name="sScript">出错提示信息</param>
        /// <param name="db">数据库链接</param>
        /// <param name="listRptID">导入报告ID</param>
        private void ExecWord_19(Microsoft.Office.Interop.Word.Document wordDoc, int IntSentenceIndex, DataTable dtCol, DataTable dtColCondition, int IntStartRowIndex, int IntStartColIndex, string

strCreater, StringBuilder sScript, clsDbAccept db, ref ArrayList listRptID)
        {
            string strDetailContent = string.Empty;
            string strMoreContent = string.Empty;
            DataRow[] rows = null;
            StringBuilder sSql2 = new StringBuilder();

             #region 取Word中表格内容
            string strSQL = "update reportDetail set detailContent='{0}',moreContent='{1}' where id='{2}' and no='{3}';";
            string strSQL2 = "update reportDetail set detailContent='{0}',moreContent='{1}' where id in ({2}) and no='{3}';";
            for (int i = 0; i < wordDoc.Tables.Count; i++)
            {
                Microsoft.Office.Interop.Word.Table wordTable = wordDoc.Tables[i + 1];
                //循环内容行
                sSql2.Clear();
                for (int row = IntStartRowIndex; row <= wordTable.Rows.Count; row++)
                {
                    string strRptID = IARREP.Create(TYPE, strCreater, db);
                    listRptID.Add(strRptID);
                    for (int col = IntStartColIndex; col <= wordTable.Columns.Count; col++)
                    {
                        strDetailContent = string.Empty;
                        strMoreContent = string.Empty;
                        string strCont = wordTable.Cell(row, col).Range.Text.Replace("\r", "").Replace("\a", "").Replace("\t", "").Trim();
                        rows = dtCol.Select(string.Format("ColIndex='{0}'", col), "");
                        if (rows != null && rows.Length > 0)
                        {
                            string strNO = rows[0]["No"].ToString();
                            string strContentType = rows[0]["ContentType"].ToString();
                            string strCol_Id = rows[0]["Col_Id"].ToString();
                            string strMaxLength = rows[0]["MaxLength"].ToString();

                            CheckItemCont(strContentType, ref strDetailContent, ref strMoreContent, strCont, strMaxLength, sScript, dtColCondition, strCol_Id, db);

                            sSql2.Append(string.Format(strSQL, strDetailContent, strMoreContent, strRptID, strNO));
                        }
                    }
                }

            }
            if (sSql2.Length > 0)
            {
                //开启事务
                db.SetTran();
                db.Execute(sSql2.ToString(), true);
                //提交事务
                db.SetCommit();
            }
        }
        #endregion
    }

 

 

/****************************************************************XML文件例子  WordImport.xml********************************************************************/

其中 <!--
Table:
TableType-表类型,18表特殊处理,否则为对应reportStruct中tableType
StartRowIndex-表格内容开始行
StartColIndex-表格内容开始列
SentenceIndex-非表格内容读取时相关,为数字。非表格数据没有时为0
Des-表描述
Col:
No-reportStruct中对应NO
ColIndex-对应表格中的列Index 0为非表格数据;非0为表格数据,对应Word表格中的列号
Title-reportStruct中对应TITLE
ContentType-reportStruct中对应CONTENTTYPE
ColCondition:
MaxLength-最长字符数
ResultColName-检索列名
TableName-检索表名
SearchColName-检索条件列
Condition-检索条件
举例:单机生产单位 select modelName from AutoComplete where groupName ='unit' 用于验证数据
-->

 

<Tables>

 <Table TableType="execWord_18D" StartRowIndex="2" StartColIndex="2" SentenceIndex="0" Des="其他型号统计表">
    <!--表格数据 Start-->

    <!--Word 元器件名称 列对应数据库中字段-->
    <Col No="61" ColIndex="2" Title="元器件名称   " ContentType="1" MaxLength="5000" ></Col>
    <!--Word 型号规格 列对应数据库中字段-->
    <Col No="62" ColIndex="3" Title="型号规格   " ContentType="1" MaxLength="5000" ></Col>
    <!--Word 批号 列对应数据库中字段-->
    <Col No="63" ColIndex="4" Title="批号" ContentType="1" MaxLength="5000" ></Col>
    <!--Word 元器件生产单位 列对应数据库中字段-->
    <Col No="64"  ColIndex="5" Title="元器件生产单位  " ContentType="12" MaxLength="5000" >
      <ColCondition ResultColName="modelName" TableName="AutoComplete" SearchColName="groupName" Condition="='unit'"></ColCondition>
    </Col>
    <!--Word 质量等级 列对应数据库中字段-->
    <Col No="65" ColIndex="6" Title="质量等级   " ContentType="1" MaxLength="5000" ></Col>
    <!--Word 所属整机名称与型号 列对应数据库中字段-->
    <Col No="66" ColIndex="7" Title="所属整机名称与型号" ContentType="1" MaxLength="5000" ></Col>
    <!--Word 失效数量 列对应数据库中字段-->
    <Col No="67" ColIndex="8" Title="失效数量" ContentType="1" MaxLength="5000" ></Col>
    <!--Word 失效性质 列对应数据库中字段-->
    <Col No="68" ColIndex="9" Title="失效性质" ContentType="1" MaxLength="5000" ></Col>
    <!--Word 失效原因 列对应数据库中字段-->
    <Col No="69" ColIndex="10" Title="失效原因" ContentType="3" MaxLength="5000" ></Col>
    <!--表格数据 End-->
  </Table>

</Tables>

 

抱歉!评论已关闭.