欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# 大数据导出word的假死报错的处理方法

程序员文章站 2023-12-03 08:50:04
最近一个项目是一个基于winform的报告系统,根据一系列的查询参数计算出结果,最终生成一个格式规范的word文档,刚开始数据量不大(500行)数据以内,写入速度还能接受,...

最近一个项目是一个基于winform的报告系统,根据一系列的查询参数计算出结果,最终生成一个格式规范的word文档,刚开始数据量不大(500行)数据以内,写入速度还能接受,但最近遇到一个问题就是当出现大量的数据行的时候,写入word的过程就变的非常慢,cpu直接拉到100%,本人机器配置已经算比较高的了,8g内存+i5cpu,依旧假死,该问题困扰了我几天,也问了google很多次,基本上给出的答案都是word本身就比较慢这样一类的答案,或者是非托管代码的优化,慢也就算了,至少可以通过进度条来交互,假死到报错,这个绝对是零容忍的。尝试了很多种方法,包括将非托管代码强制进行回收,多线程等方式,最终都失败了,当然,黄天不负有心人最终总算是解决了问题了,我的数据量不算特别巨大,就4000多行写入表中,废话少说,直接贴代码:

常规写入word表格的方法:

复制代码 代码如下:

private void loadsectionword()
        {
           //临时目录
            string filepath = tools.createwordfiledir() + utils.gettimestring() + ".doc";
          //将二进制文件写入到word文件
            sectionwordtools.byteconvertword(sectionwordtools.wordcontentbytemplateidandtemplatetitle(templateid, sectiontitle), filepath);
            try
            {
              //wdc为winwordcontrol控件的实例
                wdc.loaddocument(filepath);
                microsoft.office.interop.word.document wd = (microsoft.office.interop.word.document)wdc.document;
                microsoft.office.interop.word.application wa = wd.application;//
               //需要写入word的集合
                if (diclist.count > 0)
                {
                    diclist = diclist.orderby(d => d.key.analyteid).todictionary(i => i.key, ii => ii.value);
                    sectionwordtools.gotobookmark(wa, "repeatanalysisresult");
                    wa.selection.copy();//复制模板第一个table
                    sectionwordtools.wordreplace("special matrix", wdg.species.tolower().trim() + " " + wdg.matrix.tolower().trim(), true, wd);
                    string analytetitles = string.empty;
                    int index = 0;

                    #region replace title
                    foreach (keyvaluepair<analyterenameentity, datatable> d in diclist)
                    {

                        analyterenameentity key = d.key;
                        if (diclist.count > 2)
                        {
                            if (index.equals(diclist.count - 2))
                            {
                                analytetitles += key.newanalytename + " and ";
                            }
                            else
                            {
                                analytetitles += key.newanalytename + " , ";
                            }
                        }
                        else if (diclist.count == 2)
                        {
                            analytetitles += key.newanalytename + " and ";
                        }
                        else
                        {
                            analytetitles += key.newanalytename;
                        }
                        index++;
                    }
                    analytetitles = analytetitles.trim().trimend('d').trimend('n').trimend('a').trim().trim(',');
                    sectionwordtools.wordreplace("for abc000", "for " + analytetitles, true, wd);
                    #endregion

                    int wordtablecount = 0;
                    foreach (keyvaluepair<analyterenameentity, datatable> d in diclist)
                    {
                        analyterenameentity key = d.key;
                        dataview dv = d.value.defaultview;
                        dv.sort = "custom id";
                        datatable dt = dv.totable();
                        #region 处理dt
                        if (dt.columns["analyteid"] != null)
                        {
                            dt.columns.remove("analyteid");
                        } if (dt.columns["id"] != null)
                        {
                            dt.columns.remove("id");
                        }
                        if (dt.columns["reportid"] != null)
                        {
                            dt.columns.remove("reportid");
                        }
                        if (dt.columns["studyid"] != null)
                        {
                            dt.columns.remove("studyid");
                        }
                        if (dt.columns["analyteid"] != null)
                        {
                            dt.columns.remove("analyteid");
                        }
                        #endregion
                        //第一个wordtable
                        microsoft.office.interop.word.table tb = wd.tables[wd.tables.count];

                        #region 填充值
                        if (dt.rows.count > 0)
                        {
                            object beforerow = tb.rows[2];
                            //表头
                            for (int i = 1; i <= dt.columns.count; i++)
                            {
                                tb.cell(1, i).range.text = dt.columns[i - 1].columnname;
                            }
                            for (int k = 1; k <= dt.rows.count; k++)
                            {
                                //模板上默认有2行了,添加行数
                                if (k <= dt.rows.count - 2)
                                {
                                    tb.rows.add(ref beforerow);
                                }
                                for (int i = 1; i <= dt.columns.count; i++)
                                {
                                    tb.cell(k + 1, i).range.text = dt.rows[k - 1][dt.columns[i - 1].columnname].tostring();
                                }
                            }
                        }
                        #endregion

                        sectionwordtools.wordreplace("abc000", key.newanalytename, true, wd);

                        #region 处理备注
                        string notstr = getcurrentreassayreason(key.analyteid);
                        //notstr = "reasons for reassay:\r1). confirmation assay\r2). alq\rreasons for reported conc.:\r1). the only valid result is reported.\r20. reassay results selected according to procedure defined in study protocol";

                        sectionwordtools.wordreplace("repeat analysis tipis", notstr, true, wd);
                        #endregion
                        //根据内容调整表格
                        //tb.autofitbehavior(microsoft.office.interop.word.wdautofitbehavior.wdautofitcontent);
                        //根据窗口调整表格
                        //tb.autofitbehavior(microsoft.office.interop.word.wdautofitbehavior.wdautofitwindow);
                        if (wordtablecount < diclist.count - 1)
                        {
                            // wa.selection.typeparagraph();//回车
                            wd.paragraphs.last.range.select();
                            wa.selection.paste();
                        }
                        wordtablecount++;

                        #region 处理整体格式
                        object lefttopstr = tb.cell(2, 1).range.start;
                        object leftbottomend = tb.cell(tb.rows.count, tb.columns.count).range.end;
                        wd.range(ref lefttopstr, ref leftbottomend).select();
                        sectionwordtools.addbordernonelinestyle(wa, false, false, true, true, true, true, true, true);
                        #endregion

 

                    }


                }

            }
            catch (exception ex)
            {
                tools.recorderrorlist(ex.message, ex);
            }
        }

上面的代码就是通过winwordcontrol控件加载word模板,一行一行向word表格中写入数据,新的表格通过书签复制后粘贴,然后继续一行一行的写入,数据量在500行以内的时候,速度还是可以接受的,当数据量增大之后,就很慢了

改进后的代码,主要用到了分页的思想,将集合或者datatable进行分页,每页处理50行数据,处理完了之后保存到临时文件,释放掉word资源,再打开临时文件,接着上次的写入位置继续写入。释放word资源就是为了解决写入数据量过大假死报错的问题。希望对处理word的朋友有帮助

复制代码 代码如下:

private void loadsectionword()
        {
            string filepath = tools.createwordfiledir() + utils.gettimestring() + ".doc";
            //读取模板
            sectionwordtools.byteconvertword(sectionwordtools.wordcontentbytemplateidandtemplatetitle(templateid, sectiontitle), filepath);
            try
            {
                wdc.loaddocument(filepath);
                microsoft.office.interop.word.document wd = (microsoft.office.interop.word.document)wdc.document;
                microsoft.office.interop.word.application wa = wd.application;
                sectionwordtools.gotobookmark(wa, "timeconcentrationdata");
                wa.selection.copy();//复制模板第一个table
                string assaylloq = computerofposttext.computerposttext.getstudyassaylloqresults(this.studyid);
                sectionwordtools.wordreplace("0.0 ng/ml for abc000", assaylloq, true, wd);

                //获得分组,只有分组了的才统计,默认已经分好组,组可以调整
                list<string> grouplist = commonbll.getanalytegrouplist(this.reportid, common_type);
                list<list<analyterenameentity>> analytegrouplist = new list<list<analyterenameentity>>();

                #region 确定table分组的数量
                foreach (string group in grouplist)
                {
                    list<analyterenameentity> currentgrouplist = commonbll.getanalyterenamelist(this.reportid, this.studyid, group);
                    if (currentgrouplist.count > 0)
                    {
                        analytegrouplist.add(currentgrouplist);
                    }
                }
                #endregion

                if (analytegrouplist.count > 0)
                {
                    int wordtablecount = 0;
                    foreach (list<analyterenameentity> currentgrouplist in analytegrouplist)
                    {
                        //第一个wordtable
                        microsoft.office.interop.word.table tb = wd.tables[wd.tables.count];
                        string key = globalbll.analyteappendstring(currentgrouplist);
                        //需要写入word的结果集
                        datatable dt = new datatable();

                        #region  构造word中的列头
                        foreach (reportcolumnsentity rc in rcelist)
                        {
                            dt.columns.add(rc.reporttext, typeof(string));
                        }

                        foreach (analyterenameentity ar in currentgrouplist)
                        {
                            dt.columns.add(ar.newanalytename + " concentration (ng/ml)", typeof(string));
                        }
                        dt.columns.add("comments", typeof(string));
                        #endregion

                        #region 构造word中的行的datatable
                        for (int i = 0; i < currentgrouplist.count; i++)
                        {
                            datarow[] rows = dtresult.select(string.format(" analyteid={0}", currentgrouplist[i].analyteid));
                            if (i == 0)
                            {
                                #region i=0,填充包括列头
                                for (int k = 0; k < rows.length; k++)
                                {
                                    string conc = utils.effectivenumber(rows[k]["concentration"].tostring(), "3");
                                    datarow dr = dt.newrow();
                                    foreach (reportcolumnsentity rc in rcelist)
                                    {
                                        if (rc.watsontext.equals("concentration"))
                                        {
                                            dr[rc.reporttext] = utils.effectivenumber(rows[k][rc.watsontext].tostring(), "3");
                                        }
                                        else
                                        {
                                            dr[rc.reporttext] = rows[k][rc.watsontext].tostring();
                                        }

                                    }
                                    dr["comments"] = "na";
                                    dr[currentgrouplist[i].newanalytename + " concentration (ng/ml)"] = conc;

                                    dt.rows.add(dr);
                                }
                                #endregion
                            }
                            else
                            {
                                for (int k = 0; k < rows.length; k++)
                                {
                                    string conc = utils.effectivenumber(rows[k]["concentration"].tostring(), "3");
                                    //对分析物浓度列重新赋值
                                    dt.rows[k][currentgrouplist[i].newanalytename + " concentration (ng/ml)"] = conc;
                                }
                            }

                        }
                        datatable dttemp = dt.copy();
                        dataview dv = dt.defaultview;
                        dv.sort = "subject id";
                        dttemp = dv.totable();
                        dt = dttemp;
                        #endregion

                        #region 填充值
                        if (dt.rows.count > 0)
                        {

                            #region 根据列合并拆分单元格
                            object wordcolumnscount = dt.columns.count;
                            object rownum = 1;
                            for (int k = 0; k < 5; k++)
                            {
                                for (int i = 1; i < tb.columns.count; i++)
                                {

                                    tb.cell(k, i).range.text = " ";
                                }
                            }
                            //先合并,再拆分  selection.cells.merge
                            for (int i = 1; i <= 4; i++)
                            {
                                object start = tb.cell(i, 1).range.start;
                                object end = tb.cell(i, 6).range.end;
                                wd.range(ref start, ref end).select();
                                wa.selection.cells.merge();
                            }
                            for (int i = 1; i < 5; i++)
                            {
                                tb.cell(i, 1).split(ref rownum, ref wordcolumnscount);
                            }
                            #endregion

                            //关闭屏幕更新
                            wa.screenupdating = false;
                            #region 表头的填充
                            //表头填充
                            for (int i = 1; i <= dt.columns.count; i++)
                            {
                                tb.cell(1, i).range.text = dt.columns[i - 1].columnname;
                            }
                            #endregion

                            #region 填充值

                            #region 分页
                            object missing = system.reflection.missing.value;
                            object saveoption = microsoft.office.interop.word.wdsaveoptions.wddonotsavechanges; //解决normal.dot问题
                            object beforerow = tb.rows[3];
                            int dtrowcounts = dt.rows.count;//10;// 
                            int columncount = dt.columns.count;
                            int pagesize = 50;
                            //分页的总页数
                            int totalpages = datautils.getpagecounts(dtrowcounts, pagesize);
                            for (int index = 1; index <= totalpages; index++)
                            {
                                tb = wd.tables[wd.tables.count];
                                beforerow = tb.rows[3 + (index - 1) * pagesize];
                                datatable pagedt = datautils.getpagedtable(dt, index, pagesize);

                                #region 添加行和数据
                                for (int k = 2; k < pagedt.rows.count + 2; k++)
                                {

                                    //模板上已经有三行了,最后一页少添加3行
                                    if (index.equals(totalpages))
                                    {
                                        if (k < pagedt.rows.count - 3)
                                        {
                                            tb.rows.add(ref beforerow);
                                        }

                                    }
                                    else
                                    {
                                        tb.rows.add(ref beforerow);
                                    }
                                    //添加行的同时填充单元格的值,减少一次全循环
                                    for (int i = 1; i <= pagedt.columns.count; i++)
                                    {
                                        tb.cell(k + (index - 1) * pagesize, i).range.text = pagedt.rows[k - 2][pagedt.columns[i - 1].columnname].tostring();
                                    }
                                }
                                #endregion
                                //填充完pagesize条数据,先保存再重新加载填充
                                object savepath = filepath;
                                wd.saveas(ref   savepath, 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);
                                wa.screenupdating = true;
                                wd = null;
                                wa = null;
                                thread.sleep(10);
                                //重新加载
                                wdc.loaddocument(filepath);
                                wd = (microsoft.office.interop.word.document)wdc.document;
                                wa = wd.application;
                                wa.screenupdating = false;
                            }
                            #endregion

                            #endregion
                            //打开屏幕更新
                            //wa.activedocument.activewindow.windowstate = microsoft.office.interop.word.wdwindowstate.wdwindowstatemaximize;
                            wa.screenupdating = true;
                        }

                        #endregion

                        #region paste table
                        sectionwordtools.wordreplace("abc000", key, true, wd);
                        tb = wd.tables[wd.tables.count];
                        //根据内容调整表格
                        tb.autofitbehavior(microsoft.office.interop.word.wdautofitbehavior.wdautofitcontent);
                        //根据窗口调整表格
                        tb.autofitbehavior(microsoft.office.interop.word.wdautofitbehavior.wdautofitwindow);
                        if (wordtablecount < analytegrouplist.count - 1)
                        {
                            // wa.selection.typeparagraph();//回车
                            wd.paragraphs.last.range.select();
                            wa.selection.paste();
                        }
                        wordtablecount++;
                        #endregion
                    }
                }
            }
            catch (exception ex)
            {
                tools.recorderrorlist(ex.message, ex);
            }
        }