仰天一笑(Ansonxuyu),专业从事软件定制开发、Web软件开发,网站建设,网络推广,APP开发,微博应用开发,微信应用开发,电子商务开发,物联网开发等技术。
互联网8年风雨,愿在此交朋识友,交流心得,分享技术知识(策划/研发/运营/推广/合作)!QQ:943530498


仰天一笑

昨日不悔,今日勿失,明日莫忧! —徐羽

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  340 随笔 :: 27 文章 :: 1088 评论 :: 237万 阅读
C#操作word转成Excel数据,我先把需求详细描述一下:这位大虾写的很好,在此推荐一下,学习VBA调用的童鞋,好好看下,关于C#对word的操作和调用,C#对excel的操作和调用,加上正则表达式的调用和筛选数据,很好,值得一看。 

 

      提供一个WORD文档的样板,这个WORD文档里大部分是文本,其中插入了一个EXCEL表格,WORD的内容如下:

     

房地产价值监证确认书

 

                     编号:(2009交)价确字第   号

 邓征兵  

根据您的委托,我单位派遣专业评估人员对位于  大祥区翠园    的房地产(《房屋所有权证》)号为 0013210 ,房屋所有权人  邓文兵   房屋所在层次/总层数  6 / 8 ,进行了现场勘估。

评定估价对象房屋的结构等级为    砖混     ,建成年代为 90年代末  ,成新度为   9成   

确认房屋价值如下表:

这里有个EXCEL表格

 

监证目的:交易课税

 

备注:                                                   

                                                       

邵阳市房产产权监理处价格管理科

现场评估:黄生忠

审    批:

                                2009 年 2 月 10 日

就是把这个文件中相关内容存入数据库,同时要能够实现查询,比如根据委托人查询,同时要把查询的结果能转EXCEL。

功能就是这样的,先把其中用到的技术点挑出来,

一读WORD里的内容,这个并不难;

复制代码

Microsoft.Office.Interop.Word.ApplicationClass wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            
object file = nam;
            
object nullobj = System.Reflection.Missing.Value;
            
try
            {
                Microsoft.Office.Interop.Word.Document doc 
= wordApp.Documents.Open(
                
ref file, ref nullobj, ref nullobj,
                
ref nullobj, ref nullobj, ref nullobj,
                
ref nullobj, ref nullobj, ref nullobj,
                
ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj);

                
//doc.ActiveWindow.Selection.WholeStory();
                
                
//doc.ActiveWindow.Selection.Copy();

                
//IDataObject data = Clipboard.GetDataObject();
                
                fileContent 
= doc.Content.Text;   //这里读取所有的WORD里的文本             
}
复制代码

 

二读WORD文件里EXCEL里的数据,这个是比较困难的,我试了很多方式,也没有查到相关的资料,最后在国外论坛上看见了VB的代码,然后修改了一下,可以用;

复制代码

foreach (Microsoft.Office.Interop.Word.InlineShape ish in doc.InlineShapes)
                {
                    
if (ish.Type == Microsoft.Office.Interop.Word.WdInlineShapeType.wdInlineShapeEmbeddedOLEObject)
                    {
                        
if (ish.OLEFormat.ProgID == "Excel.Sheet.8")
                        {
                            
//ish.OLEFormat.DoVerb(ref nullobj);

                            ish.OLEFormat.Activate();
                            Microsoft.Office.Interop.Excel.Workbook objEXl 
= (Microsoft.Office.Interop.Excel.Workbook)ish.OLEFormat.Object;
                            buildArea 
= ((objEXl.Worksheets[1as Microsoft.Office.Interop.Excel.Worksheet).Cells[22as Microsoft.Office.Interop.Excel.Range).Text.ToString();
                            
if (buildArea != "")
                            {
                                buildUnitPrice 
= ((objEXl.Worksheets[1as Microsoft.Office.Interop.Excel.Worksheet).Cells[23as Microsoft.Office.Interop.Excel.Range).Text.ToString();
                                buildCountPrice 
= ((objEXl.Worksheets[1as Microsoft.Office.Interop.Excel.Worksheet).Cells[24as Microsoft.Office.Interop.Excel.Range).Text.ToString();
                                userKind 
= "住宅";
                            }
                            
else
                            {
                                buildArea 
= ((objEXl.Worksheets[1as Microsoft.Office.Interop.Excel.Worksheet).Cells[32as Microsoft.Office.Interop.Excel.Range).Text.ToString();
                                buildUnitPrice 
= ((objEXl.Worksheets[1as Microsoft.Office.Interop.Excel.Worksheet).Cells[33as Microsoft.Office.Interop.Excel.Range).Text.ToString();
                                buildCountPrice 
= ((objEXl.Worksheets[1as Microsoft.Office.Interop.Excel.Worksheet).Cells[34as Microsoft.Office.Interop.Excel.Range).Text.ToString();
                                userKind 
= "非住宅";
                            }                            
                            objEXl.Application.Quit();                            
                        }
                    }
                }
复制代码

 

 

三正则表达式的应用,我要获取比如邓征兵这个委托人,我不可能用SUBSTRING来取数据吧,这样效果太低了;

复制代码

Regex reg1 = new Regex("[\u4E00-\u9FFF]+", RegexOptions.IgnoreCase);
                userName 
= reg1.Match(doc.Paragraphs[4].Range.Text).Value.Trim();//委托人
                Regex reg2 = new Regex("评估人员对位于([\\S|\\s]+)的房地产", RegexOptions.IgnoreCase);
                HouseAddr 
= reg2.Match(fileContent).Groups[1].Value.Trim();//房子地址doc.Paragraphs[5].Range.Text
                Regex reg3 = new Regex("号为([\\S|\\s]+),房屋所有权人", RegexOptions.IgnoreCase);
                propertyNo 
= reg3.Match(fileContent).Groups[1].Value.Trim();//房产证号doc.Paragraphs[5].Range.Text
                Regex reg4 = new Regex("房屋所有权人([\\S|\\s]+)房屋所在层次", RegexOptions.IgnoreCase);
                propertyUser 
= reg4.Match(fileContent).Groups[1].Value.Trim();//房屋所有权人doc.Paragraphs[5].Range.Text
                Regex reg5 = new Regex("层次/总层数([\\S|\\s]+),进行了现场勘估", RegexOptions.IgnoreCase);
                buildCount 
= reg5.Match(fileContent).Groups[1].Value.Trim();//层次/总层数doc.Paragraphs[5].Range.Text
                Regex reg6 = new Regex("建成年代为([\\S|\\s]+),成新度为", RegexOptions.IgnoreCase);
                buildYear 
= reg6.Match(fileContent).Groups[1].Value.Trim();//建成年代doc.Paragraphs[6].Range.Text
                Regex reg7 = new Regex("现场评估:([\\S|\\s]+)审", RegexOptions.IgnoreCase);
                evaluateUser 
= reg7.Match(fileContent).Groups[1].Value.Trim();//现场评估doc.Paragraphs[13].Range.Text
                Regex reg8 = new Regex("[\\d|\\s]+年[\\d|\\s]+月[\\d|\\s]+日", RegexOptions.IgnoreCase);
                evaluateDate 
= reg8.Match(fileContent).Value.Trim();//doc.Paragraphs[15].Range.Text.Trim()时间
复制代码

 

四转EXCEL,网上很多人都是用datagrid直接转EXCEL,这样只能倒出第一页的数据,不适合我的程序;

复制代码

DataTable dt = GetAllData();
        StringWriter sw 
= new StringWriter();
        sw.WriteLine(
"序号\t委托方\t产权人\t产权证号\t房屋座落\t建筑面积(平方米)\t建成年代\t层次/层数\t使用性质\t评估单价(元/平方米)\t评估总价值(元)\t现场评估人员\t评估日期\t备注");

        
if (dt != null)
        {
            
foreach (DataRow dr in dt.Rows)
            {
                sw.WriteLine(dr[
"id"+ "\t" + dr["userName"+ "\t" + dr["propertyUser"+ "\t" + dr["propertyNo"+ "\t" +
                    dr[
"HouseAddr"+ "\t" + dr["buildArea"+ "\t" + dr["buildYear"+ "\t" + dr["buildCount"+ "\t" +
                    dr[
"userKind"+ "\t" + dr["buildUnitPrice"+ "\t" + dr["buildCountPrice"+ "\t" + dr["evaluateUser"]
                    
+ "\t" + dr["evaluateDate"+ "\t" + "");
            }
        }
        sw.Close();
        Response.AddHeader(
"content-disposition""attachment; filename=MyExcelFile.xls");
        Response.ContentType 
= "application/excel";
        Response.ContentEncoding 
= System.Text.Encoding.GetEncoding("GB2312");
        Response.Write(sw);
        Response.End();
复制代码

 

五,KILL进程,我在查看WORD里EXCEL里的数据的时候,无法关闭EXCEL,需要用程序来关闭;

复制代码

public void KillProcess(string processName)
    {
        System.Diagnostics.Process myproc 
= new System.Diagnostics.Process();
        
//得到所有打开的进程  
        try
        {
            
foreach (Process thisproc in Process.GetProcessesByName(processName))
            {
                
if (!thisproc.CloseMainWindow())
                {
                    
if (thisproc != null)
                        thisproc.Kill();
                }
            }
        }
        
catch (Exception Exc)
        {
            
throw Exc;
            
// msg.Text+=  "杀死"  +  processName  +  "失败!";  
        }
    }  
复制代码
详细技术点请下载
 
posted on   仰天一笑  阅读(3510)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示