010 Ruby Excel逐行写入Word

  |   0浏览

v2-12dc705dd3fb83025ba302347203be88_720w.jpg

上期,我们讲解了如何从Word题库将题干、选项、答案分离,并在excel里保存。

很多时候我们整理了一套Excel试题题库,想生成一套试卷进行自我测评,如果自己手工整理,2天2夜也做不完。

这期,我们就一起看一看。

如何使用Ruby,20秒内完成一套150题的试卷输出。

【Python,我都没学会,又想骗我学Ruby?】——笑cry~

其实,某些情况下,Ruby确实比Python好用,仁者见仁智者见智。

001 需求分析

v2-0146ffdf3dae5ca4e9954a3b4006a20a_720w.jpg

如图所示,我需要将Excel转换为Word。我该怎么做呢?

v2-bc04d95deaa3c82f0ac7e66a6ec010b3_720w.jpg

002 思路解析

很显然,我们先把Excel区域读入内存数组,再通过循环建立Wdc.paragraphs(m).range.textarr[i][j]的连接即可。

v2-f13368047348b61678d64620bf0195b5_720w.jpg

003 源码展示

require 'win32ole'Pth=File.dirname(__FILE__)  Eap=WIN32OLE::new('Excel.Application');Eap.visible=trueEbk=Eap.workbooks.open(Pth+'/excel.xls')Wap=WIN32OLE::new('word.Application');Wap.visible=trueWdc=Wap.documents.open(Pth+'/题库.doc')arr=Arrayarr=Ebk.worksheets(1).range('a1:g150').valuem=1;(0..149).each{|i|    (0..6).each{|j|      if arr[i][j]!=nil         Wdc.paragraphs(m).range.text=arr[i][j]        m+=1      end    }  }

附:第9期 C#实现Word->Excel的方法演示代码。

using System;using System.IO; using System.Diagnostics;using Word=Microsoft.Office.Interop.Word;using Excel=Microsoft.Office.Interop.Excel;namespace tiku_to_excel{  class Program  {    public static void Main(string[] args)    {      Stopwatch timer = new Stopwatch();            timer.Start();                  string Pth=AppDomain.CurrentDomain.BaseDirectory;      Word._Application Wap = new Word.Application();Wap.Visible=true;        Word._Document Wdc = Wap.Documents.Open(Pth + @'/2020年安全生产月全国安全知识网络竞赛活动题库.doc');      string s1='A.';      string s4='D.';      string s5='正确答案';      string [,] arr= new string [150,7];      int t = Wdc.Paragraphs.Count;               int i=0;                  for(int j = 1 ;j<=t;j++)            {              Word.Paragraph Wph = Wdc.Paragraphs[j];              if (Wph.Range.Text.IndexOf(s1)==0)                {                  arr[i,0] = Wdc.Paragraphs[j-2].Range.Text;                  arr[i,1] = Wdc.Paragraphs[j-1].Range.Text;                arr[i,2] = Wdc.Paragraphs[j].Range.Text;                  arr[i,3] = Wdc.Paragraphs[j+1].Range.Text;                  arr[i,4] = Wdc.Paragraphs[j+2].Range.Text;              }                else if(Wph.Range.Text.IndexOf(s4)==0)                {                  arr[i,5] = Wph.Range.Text;                }                else if(Wph.Range.Text.IndexOf(s5)==0)                {                  arr[i,6] = Wph.Range.Text;                  i++;                }              }      Excel._Application Eap = new Excel.Application();Eap.Visible=true;      Excel._Workbook Ebk = Eap.Workbooks.Open( Pth + @'/tiku_to_excel.xls');      Ebk.Worksheets[1].Range('A1').Resize(150,7).value=arr;      timer.Stop();      Console.WriteLine('使用C#用时:'+timer.Elapsed.TotalSeconds+' 秒');      Console.ReadLine();    }  }}

原文地址:https://blog.51cto.com/14823672/2506728