C#操作Word(打开创建,选择复制,写入数据,保存关闭)

(1)必要变量(字段)定义

 private object Nothing = Missing.Value;//缺省值
 private object IsReadOnly = false;//不仅仅可读
 private MSWord._Application wordApp;//Word应用程序
 private MSWord._Document wordDoc;//Word文档
 private int tableCount;//Word表格数目(完整的)
 注:前面4个是操作Word时,必须定义的字段;最后一个适应本程序

(2)读取txt数据

//原始数据读取
        private List<string> TextData = new List<string>();//文本数据(去除41000……)
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            openFileDialog1.InitialDirectory = "E:\\";
            openFileDialog1.Filter = "GSI(*.gsi)|*.gsi";
            if(openFileDialog1.ShowDialog()==DialogResult.OK)
            {
                TextData = File.ReadAllLines(openFileDialog1.FileName).Where(s => (s[0] != '4') && (s != "")).ToList();
            }
            tableCount = (int)(TextData.Count / 11 * 2 / 7);
            MessageBox.Show("共读取" + TextData.Count / 11 + "测段的数据!");
        }

(3)打开原本的Word文档,并复制其中的表格

//加载水准簿(并进行表格复制)
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            openFileDialog2.InitialDirectory = "e:\\";
            openFileDialog2.Filter = "文档(*.docx)|*.docx|(*.doc)|*.doc";
            if(openFileDialog2.ShowDialog()==DialogResult.OK)
            {
                try
                {
                    foreach (Process item in Process.GetProcessesByName("WINWORD"))
                    { item.Kill(); }//如存在打开的Word则先关闭(一个应用程序实例就是进程)
                    object filePath=openFileDialog2.FileName;
                    wordApp = new MSWord.Application(); //应用程序实例化
                    //wordApp.Visible = true;//可见(用的是wordApp显示)
                    wordDoc = wordApp.Documents.Open(ref filePath, ref Nothing, ref IsReadOnly, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);

                    wordDoc.Tables[1].Select();//选择与复制:文档用Sections[节]/应用程序用Selection[选择]
                    wordApp.Selection.Copy();
                    //////还可以是:(会复制文档第一部分所有内容--包括标题)
                    //wordDoc.Select();
                    //wordDoc.Sections[1].Range.Copy();
                    //wordDoc.Sections[1].Range.InsertBreak(ref myType); //以页为单元,表格连续(只复制表格)
                    //wordDoc.Sections[1].Range.PasteAndFormat(MSWord.WdRecoveryType.wdPasteDefaul);//复制语句:文档形式

                    object myType = MSWord.WdBreakType.wdSectionBreakContinuous;//换行符
                    object myUnit = MSWord.WdUnits.wdStory;
                    object pBreak = (int)MSWord.WdBreakType.wdPageBreak;//下一页(上一页最后一行空,否则跳入下下页)

                    //object start = wordApp.ActiveWindow.Selection.End;//定位文档末尾
                    //object end = wordApp.ActiveWindow.Selection.End;
                    //MSWord.Range rng = wordDoc.Range(ref start, ref end);
                    //rng.Select();  
                    //rng.Paste();  

                    for (int i = 0; i < tableCount-1;i++ )//原本手簿已存在一个,则复制减1个
                    {
                        wordApp.Selection.EndKey(ref myUnit, ref Nothing);
                        wordApp.Selection.InsertBreak(ref pBreak);
                        wordApp.Selection.PasteAndFormat(MSWord.WdRecoveryType.wdPasteDefault);//复制语句:应用程序形式
                        //wordApp.Selection.Paste();//复制语句:简单形式
                    }
                        MessageBox.Show("手簿加载完成!");
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

(4)将txt数据写入变化后的Word文档并保存

//原始数据:TextData中
        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            try
            {
                #region 文档头
                object bm1 = "云量";
                wordDoc.Bookmarks.get_Item(ref bm1).Range.Text = "多云";
                object bm2 = "风向风速";
                wordDoc.Bookmarks.get_Item(ref bm2).Range.Text = "无风";
                object bm3 = "天气";
                wordDoc.Bookmarks.get_Item(ref bm3).Range.Text = "晴朗";
                #endregion
                List<string> Data = TextData.Where(s => s.ToCharArray().Count() > 35).ToList();//全部都是5行5行的 
                int tabturn = 0;//表格计数
                foreach(MSWord.Table table in wordDoc.Tables)
                {
                    for (int i = 1; i < 8; i++)
                    {
                        List<string> tempData = new List<string>();
                        for (int j = 35 * tabturn + (i - 1) * 5; j < 35 * tabturn + i * 5; j++)
                        {
                            tempData.Add(Data[j]);
                        }
                        #region 文档表格赋值
                        table.Cell(4 * i + 1, 1).Range.Text = i + "测站";
                        table.Cell(4 * i + 1, 5).Range.Text = (double.Parse(tempData[0].Trim().Split(' ')[2].Substring(6, 9)) / 100.0).ToString();//后尺基本(mm)
                        table.Cell(4 * i + 2, 5).Range.Text = (double.Parse(tempData[1].Trim().Split(' ')[2].Substring(6, 9)) / 100.0).ToString();//前尺基本(mm)
                        table.Cell(4 * i + 2, 6).Range.Text = (double.Parse(tempData[2].Trim().Split(' ')[2].Substring(6, 9)) / 100.0).ToString();//前尺辅助(mm)
                        table.Cell(4 * i + 1, 6).Range.Text = (double.Parse(tempData[3].Trim().Split(' ')[2].Substring(6, 9)) / 100.0).ToString();//后尺辅助(mm)
                        table.Cell(4 * i + 3, 2).Range.Text = ((double.Parse(tempData[0].Trim().Split(' ')[1].Substring(6, 9)) / 1e2 + double.Parse(tempData[3].Trim().Split(' ')[1].Substring(6, 9)) / 1e2) / 2).ToString();//后视距离(mm)
                        table.Cell(4 * i + 3, 3).Range.Text = ((double.Parse(tempData[1].Trim().Split(' ')[1].Substring(6, 9)) / 1e2 + double.Parse(tempData[2].Trim().Split(' ')[1].Substring(6, 9)) / 1e2) / 2).ToString();//前视距离(mm)
                        table.Cell(4 * i + 4, 2).Range.Text = ((int)(((double.Parse(tempData[0].Trim().Split(' ')[1].Substring(6, 9)) / 1e5 + double.Parse(tempData[3].Trim().Split(' ')[1].Substring(6, 9)) / 1e5) / 2 - (double.Parse(tempData[1].Trim().Split(' ')[1].Substring(6, 9)) / 1e5 + double.Parse(tempData[2].Trim().Split(' ')[1].Substring(6, 9)) / 1e5) / 2) * 10000 + 0.5) / 10000.0).ToString();//后前视距离差(m)
                        table.Cell(4 * i + 4, 3).Range.Text = (double.Parse(tempData[4].Trim().Split(' ')[3].Substring(6, 9)) / 1e5).ToString();//前后视距差累积(m)
                        table.Cell(4 * i + 1, 7).Range.Text = ((int)((double.Parse(tempData[0].Trim().Split(' ')[2].Substring(6, 9)) / 100.0 - double.Parse(tempData[3].Trim().Split(' ')[2].Substring(6, 9)) / 100.0) * 1000 + 0.5) / 1000.0).ToString();//基+K-辅(mm)
                        table.Cell(4 * i + 2, 7).Range.Text = ((int)((double.Parse(tempData[1].Trim().Split(' ')[2].Substring(6, 9)) / 100.0 - double.Parse(tempData[2].Trim().Split(' ')[2].Substring(6, 9)) / 100.0) * 1000 + 0.5) / 1000.0).ToString();//基+K-辅(mm)
                        table.Cell(4 * i + 3, 5).Range.Text = ((int)((double.Parse(tempData[0].Trim().Split(' ')[2].Substring(6, 9)) / 100.0 - double.Parse(tempData[1].Trim().Split(' ')[2].Substring(6, 9)) / 100.0) * 10000 + 0.5) / 10000.0).ToString(); //后-前(基本mm)
                        table.Cell(4 * i + 3, 6).Range.Text = ((int)((double.Parse(tempData[3].Trim().Split(' ')[2].Substring(6, 9)) / 100.0 - double.Parse(tempData[2].Trim().Split(' ')[2].Substring(6, 9)) / 100.0) * 10000 + 0.5) / 10000.0).ToString(); //后-前(辅助mm)
                        table.Cell(4 * i + 3, 7).Range.Text = ((int)((double.Parse(tempData[0].Trim().Split(' ')[2].Substring(6, 9)) / 100.0 - double.Parse(tempData[3].Trim().Split(' ')[2].Substring(6, 9)) / 100.0 - (double.Parse(tempData[1].Trim().Split(' ')[2].Substring(6, 9)) / 100.0 - double.Parse(tempData[2].Trim().Split(' ')[2].Substring(6, 9)) / 100.0)) * 1000 + 0.5) / 1000.0).ToString(); //检核
                        table.Cell(4 * i + 4, 6).Range.Text = (double.Parse(tempData[4].Trim().Split(' ')[5].Substring(6, 9)) / 1e5).ToString();//高差
                        #endregion
                    }
                    tabturn += 1;
                }

                //文档另存为并退出
                saveFileDialog1.Filter = "文档(*.docx)|*.docx|(*.doc)|*.doc";
                if(saveFileDialog1.ShowDialog()==DialogResult.OK)
                {
                    object filePath = saveFileDialog1.FileName;
                    object format = MSWord.WdSaveFormat.wdFormatDocumentDefault;//docx
                    //object format = MSWord.WdSaveFormat.wdFormatDocument;//doc
                    wordDoc.SaveAs(ref filePath, ref format, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
                    ((MSWord._Document)wordDoc).Close(ref Nothing, ref Nothing, ref Nothing);
                    ((MSWord._Application)wordApp).Quit(ref Nothing, ref Nothing, ref Nothing);
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                if (wordApp != null)
                {
                    Marshal.FinalReleaseComObject(wordApp);
                    wordApp = null;
                }

                if (wordDoc != null)
                {
                    Marshal.FinalReleaseComObject(wordDoc);
                    wordDoc = null;
                }
            }
        }
注:当向Word表格中输入数据时,循环处代码较多,但本质上并不复杂。

(5)部分txt文本数据(莱卡数字水准仪数据)

410001+?......2 
110002+000000A1 83..28+00000000 
110003+000000A1 32...8+01471340 331.08+00096547 390...+00000002 391.08+00000000 71....+00000001 
110004+00000001 32...8+01457115 332.08+00144543 390...+00000002 391.08+00000005 
110005+00000001 32...8+01456595 336.08+00144553 390...+00000002 391.08+00000002 
110006+000000A1 32...8+01470969 335.08+00096549 390...+00000002 391.08+00000001 
110007+00000001 571.08+00000008 572.08+00000008 573..8+00014300 574..8+02928010 83..08-00048000 
110008+00000001 32...8+01616093 331.08+00143847 390...+00000002 391.08+00000001 
110009+00000002 32...8+01626730 332.08+00136480 390...+00000002 391.08+00000000 
110010+00000002 32...8+01626589 336.08+00136477 390...+00000002 391.08+00000001 
110011+00000001 32...8+01616202 335.08+00143831 390...+00000002 391.08+00000024 
110012+00000002 571.08+00000013 572.08+00000021 573..8+00003788 574..8+06170816 83..08-00040640 
410013+?......2 
110014+000000A1 83..08+00000000 
110015+000000A1 32...8+01625880 331.08+00136485 390...+00000002 391.08+00000003 
110016+00000001 32...8+01617791 332.08+00143837 390...+00000002 391.08+00000004 
110017+00000001 32...8+01617711 336.08+00143834 390...+00000002 391.08+00000003 
110018+000000A1 32...8+01624988 335.08+00136499 390...+00000002 391.08+00000002 
110019+00000001 571.08-00000017 572.08-00000017 573..8+00007683 574..8+03243185 83..08-00007344 
110020+00000001 32...8+01460178 331.08+00144567 390...+00000002 391.08+00000001 
110021+00000002 32...8+01469076 332.08+00096601 390...+00000002 391.08+00000000 
110022+00000002 32...8+01469139 336.08+00096599 390...+00000002 391.08+00000002 
110023+00000001 32...8+01460232 335.08+00144565 390...+00000002 391.08+00000001 
110024+00000002 571.08-00000001 572.08-00000018 573..8-00001220 574..8+06172497 83..08+00040622 

(6)部分结果截图

result

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C_xxy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值