国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

使用NOPI讀取Word、Excel文檔內(nèi)容

2020-01-24 00:19:41
字體:
供稿:網(wǎng)友

使用NOPI讀取Excel的例子很多,讀取Word的例子不多。

Excel的解析方式有多中,可以使用ODBC查詢,把Excel作為一個數(shù)據(jù)集對待。也可以使用文檔結(jié)構(gòu)模型的方式進(jìn)行解析,即解析Workbook(工作簿)、Sheet、Row、Column。

Word的解析比較復(fù)雜,因為Word的文檔結(jié)構(gòu)模型定義較為復(fù)雜。解析Word或者Excel,關(guān)鍵是理解Word、Excel的文檔對象模型。

Word、Excel文檔對象模型的解析,可以通過COM接口調(diào)用,此類方式使用較廣。(可以錄制宏代碼,然后替換為對應(yīng)的語言)

也可以使用XML模型解析,尤其是對于2007、2010版本的文檔的解析。

using NPOI.POIFS.FileSystem;using NPOI.SS.UserModel;using NPOI.XSSF.UserModel;using NPOI.XWPF.UserModel;using System;using System.Collections.Generic;using System.Configuration;using System.IO;using System.Text;namespace eyuan{  public static class NOPIHandler  {    /// <summary>    ///     /// </summary>    /// <param name="fileName"></param>    /// <returns></returns>    public static List<List<List<string>>> ReadExcel(string fileName)    {      //打開Excel工作簿      XSSFWorkbook hssfworkbook = null;      try      {        using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))        {          hssfworkbook = new XSSFWorkbook(file);        }      }      catch (Exception e)      {        LogHandler.LogWrite(string.Format("文件{0}打開失敗,錯誤:{1}", new string[] { fileName, e.ToString() }));      }      //循環(huán)Sheet頁      int sheetsCount = hssfworkbook.NumberOfSheets;      List<List<List<string>>> workBookContent = new List<List<List<string>>>();      for (int i = 0; i < sheetsCount; i++)      {        //Sheet索引從0開始        ISheet sheet = hssfworkbook.GetSheetAt(i);        //循環(huán)行        List<List<string>> sheetContent = new List<List<string>>();        int rowCount = sheet.PhysicalNumberOfRows;        for (int j = 0; j < rowCount; j++)        {          //Row(邏輯行)的索引從0開始          IRow row = sheet.GetRow(j);          //循環(huán)列(各行的列數(shù)可能不同)          List<string> rowContent = new List<string>();          int cellCount = row.PhysicalNumberOfCells;          for (int k = 0; k < cellCount; k++)          {            //ICell cell = row.GetCell(k);            ICell cell = row.Cells[k];            if (cell == null)            {              rowContent.Add("NIL");            }            else            {              rowContent.Add(cell.ToString());              //rowContent.Add(cell.StringCellValue);            }          }          //添加行到集合中          sheetContent.Add(rowContent);        }        //添加Sheet到集合中        workBookContent.Add(sheetContent);      }      return workBookContent;    }    /// <summary>    ///     /// </summary>    /// <param name="fileName"></param>    /// <returns></returns>    public static string ReadExcelText(string fileName)    {      string ExcelCellSeparator = ConfigurationManager.AppSettings["ExcelCellSeparator"];      string ExcelRowSeparator = ConfigurationManager.AppSettings["ExcelRowSeparator"];      string ExcelSheetSeparator = ConfigurationManager.AppSettings["ExcelSheetSeparator"];      //      List<List<List<string>>> excelContent = ReadExcel(fileName);      string fileText = string.Empty;      StringBuilder sbFileText = new StringBuilder();      //循環(huán)處理WorkBook中的各Sheet頁      List<List<List<string>>>.Enumerator enumeratorWorkBook = excelContent.GetEnumerator();      while (enumeratorWorkBook.MoveNext())      {        //循環(huán)處理當(dāng)期Sheet頁中的各行        List<List<string>>.Enumerator enumeratorSheet = enumeratorWorkBook.Current.GetEnumerator();        while (enumeratorSheet.MoveNext())        {          string[] rowContent = enumeratorSheet.Current.ToArray();          sbFileText.Append(string.Join(ExcelCellSeparator, rowContent));          sbFileText.Append(ExcelRowSeparator);        }        sbFileText.Append(ExcelSheetSeparator);      }      //      fileText = sbFileText.ToString();      return fileText;    }    /// <summary>    /// 讀取Word內(nèi)容    /// </summary>    /// <param name="fileName"></param>    /// <returns></returns>    public static string ReadWordText(string fileName)    {      string WordTableCellSeparator = ConfigurationManager.AppSettings["WordTableCellSeparator"];      string WordTableRowSeparator = ConfigurationManager.AppSettings["WordTableRowSeparator"];      string WordTableSeparator = ConfigurationManager.AppSettings["WordTableSeparator"];      //      string CaptureWordHeader = ConfigurationManager.AppSettings["CaptureWordHeader"];      string CaptureWordFooter = ConfigurationManager.AppSettings["CaptureWordFooter"];      string CaptureWordTable = ConfigurationManager.AppSettings["CaptureWordTable"];      string CaptureWordImage = ConfigurationManager.AppSettings["CaptureWordImage"];      //      string CaptureWordImageFileName = ConfigurationManager.AppSettings["CaptureWordImageFileName"];      //      string fileText = string.Empty;      StringBuilder sbFileText = new StringBuilder();      #region 打開文檔      XWPFDocument document = null;      try      {        using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))        {          document = new XWPFDocument(file);        }      }      catch (Exception e)      {        LogHandler.LogWrite(string.Format("文件{0}打開失敗,錯誤:{1}", new string[] { fileName, e.ToString() }));      }      #endregion      #region 頁眉、頁腳      //頁眉      if (CaptureWordHeader == "true")      {        sbFileText.AppendLine("Capture Header Begin");        foreach (XWPFHeader xwpfHeader in document.HeaderList)        {          sbFileText.AppendLine(string.Format("{0}", new string[] { xwpfHeader.Text }));        }        sbFileText.AppendLine("Capture Header End");      }      //頁腳      if (CaptureWordFooter == "true")      {        sbFileText.AppendLine("Capture Footer Begin");        foreach (XWPFFooter xwpfFooter in document.FooterList)        {          sbFileText.AppendLine(string.Format("{0}", new string[] { xwpfFooter.Text }));        }        sbFileText.AppendLine("Capture Footer End");      }      #endregion      #region 表格      if (CaptureWordTable == "true")      {        sbFileText.AppendLine("Capture Table Begin");        foreach (XWPFTable table in document.Tables)        {          //循環(huán)表格行          foreach (XWPFTableRow row in table.Rows)          {            foreach (XWPFTableCell cell in row.GetTableCells())            {              sbFileText.Append(cell.GetText());              //              sbFileText.Append(WordTableCellSeparator);            }            sbFileText.Append(WordTableRowSeparator);          }          sbFileText.Append(WordTableSeparator);        }        sbFileText.AppendLine("Capture Table End");      }      #endregion      #region 圖片      if (CaptureWordImage == "true")      {        sbFileText.AppendLine("Capture Image Begin");        foreach (XWPFPictureData pictureData in document.AllPictures)        {          string picExtName = pictureData.suggestFileExtension();          string picFileName = pictureData.GetFileName();          byte[] picFileContent = pictureData.GetData();          //          string picTempName = string.Format(CaptureWordImageFileName, new string[] { Guid.NewGuid().ToString() + "_" + picFileName + "." + picExtName });          //          using (FileStream fs = new FileStream(picTempName, FileMode.Create, FileAccess.Write))          {            fs.Write(picFileContent, 0, picFileContent.Length);            fs.Close();          }          //          sbFileText.AppendLine(picTempName);        }        sbFileText.AppendLine("Capture Image End");      }      #endregion      //正文段落      sbFileText.AppendLine("Capture Paragraph Begin");      foreach (XWPFParagraph paragraph in document.Paragraphs)      {        sbFileText.AppendLine(paragraph.ParagraphText);      }      sbFileText.AppendLine("Capture Paragraph End");      //      //      fileText = sbFileText.ToString();      return fileText;    }  }}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 钟祥市| 凯里市| 神木县| 吉林省| 黎城县| 工布江达县| 曲麻莱县| 敦煌市| 如皋市| 汝州市| 杨浦区| 义马市| 方正县| 名山县| 霍邱县| 大英县| 常德市| 迭部县| 宜春市| 呼玛县| 隆子县| 浦北县| 鄂温| 蓬莱市| 辽源市| 永胜县| 玛曲县| 甘谷县| 镇宁| 永新县| 桐乡市| 岗巴县| 婺源县| 眉山市| 奉化市| 甘孜县| 八宿县| 凤庆县| 普安县| 祁连县| 陵川县|