[Office][C#] NPOI、OpenXML SDK、OpenOffice.org SDK 寫入資料到 EXCEL 檔案

一、簡介

要將資料寫入 EXCEL 檔案有許多的方法,但假如電腦不想安裝 Microsoft Office EXCEL,又想要寫入資料到 EXCEL,可以使用 NPOI、OpenXML SDK、OpenOffice.org SDK 等方式。本文透過簡單的範例 - 寫入資料到 EXCEL 讓大家初步了解如何使用這些 Library。

附註 : 本文程式為 Windows Forms (.NET Framework 3.5 專案),開發環境為 Windows XP SP3、Visual Studio 2008 SP1。

 

 

二、NPOI

NPOI 是可在 .NET 上的處理 Office 檔案的函式庫,由於 NPOI 相當熱門,因此不多加介紹,有興趣的可以參考小朱的文章 在 Server 端存取 Excel 檔案的利器:NPOI Library,而在使用上能讀寫 xls 檔案。接著介紹如何使用 NPOI 寫入資料到 EXCEL (xls) 檔案。

1. NOPI 下載與加入參考

(1) 到 CodePlex 的 NPOI 網站中下載 NPOI Lirary,在此下載的是 NPOI 1.2.2 for .NET 2.0,下載並且壓縮後,會有 7 個 dll 檔案,分別是

  • NPOI.dll:NPOI 核心函式庫。
  • NPOI.DDF.dll:NPOI 繪圖區讀寫函式庫。
  • NPOI.HPSF.dll:NPOI 文件摘要資訊讀寫函式庫。
  • NPOI.HSSF.dll:NPOI Excel BIFF 檔案讀寫函式庫。
  • NPOI.Util.dll:NPOI 工具函式庫。
  • NPOI.POIFS.dll:NPOI OLE 格式存取函式庫。
  • ICSharpCode.SharpZipLib.dll:檔案壓縮函式庫。

(2) 解壓縮後,將 NPOI 的 dll 加入參考中。

image image

 

2. 程式撰寫

請參考以下程式碼與註解,了解如何透過 NPOI 寫入資料到 Excel 檔案,以下程式為建立工作簿、工作表、寫入資料、儲存檔案。

01 using System;
02 using System.Collections.Generic;
03 using System.ComponentModel;
04 using System.Data;
05 using System.Drawing;
06 using System.Linq;
07 using System.Text;
08 using System.Windows.Forms;
09  
10 using System.IO;
11  
12 #region NPOI
13 using NPOI.HSSF.UserModel;
14 using NPOI.HPSF;
15 using NPOI.POIFS.FileSystem;
16 #endregion NPOI
17  
18 namespace WinFormNPOI
19 {
20     public partial class Form1 : Form
21     {
22         public Form1()
23         {
24             InitializeComponent();
25         }
26  
27         private void btnNPOI_Click(object sender, EventArgs e)
28         {
29             // 建立新的 Excel 工作簿
30             HSSFWorkbook hssfworkbook = new HSSFWorkbook();
31  
32             // 在 Excel 工作簿中建立工作表,名稱為 Sheet1
33             HSSFSheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
34  
35             // 寫入資料到工作表中
36             sheet1.CreateRow(1).CreateCell(1).SetCellValue("點部落");
37             sheet1.CreateRow(2).CreateCell(1).SetCellValue("小歐ou");
38   
39             // 儲存檔案
40             FileStream file = new FileStream(@"C:\NPOI.xls", FileMode.Create);
41             hssfworkbook.Write(file);
42             file.Close();
43         }
44     }
45 }

 

3. 執行結果

image

 

 

三、OpenXML SDK

Open XML SDK 是微軟所提供可以用來處理 Office 檔案,但只限 Open XML 檔案格式 (以 Excel 來說副檔名為 xlsx)。

目前 Open XML Format SDK 有以下版本

 

接著介紹如何使用 OpenXML SDK 寫入資料到 EXCEL (xlsx) 檔案。

1. OpenXML SDK 下載與加入參考

(1) 連結到 Open XML Format SDK 2.0 進行下載

image

image_thumb6

 

(2) 執行 OpenXMLSDKv2.msi 進行安裝,安裝過程並沒有特別的過程,只是要記得安裝路徑在哪,免得找不到 dll。

image  image

image  image

image

(3) 將 DocumentFormat.OpenXml.dll、WindowsBase.dll 加入參考

DocumentFormat.OpenXml.dll 位置在 C:\Program Files\Open XML SDK\V2.0\lib\DocumentFormat.OpenXml.dll

image  image

image

 

2. 程式撰寫

參考程式碼與註解說明,程式流程如下

(1) 開啟 Excel 檔案,取得工作簿

(2) 取得工作簿中的工作表,並透過 Linq 判斷工作表是否存在

(3) 建立 Cell 物件,設定寫入位置,格式,資料

(4) 建立 Row 物件,將 Cell 加入

(5) 將 Row 加入工作表中

(6) 儲存檔案

01 using System;
02 using System.Collections.Generic;
03 using System.ComponentModel;
04 using System.Data;
05 using System.Drawing;
06 using System.Linq;
07 using System.Text;
08 using System.Windows.Forms;
09  
10 #region OpenXML SDK
11 using DocumentFormat.OpenXml.Packaging;
12 using DocumentFormat.OpenXml.Spreadsheet;
13 using DocumentFormat.OpenXml;
14 #endregion OpenXML SDK
15  
16 namespace WinFormOpenXML
17 {
18     public partial class Form1 : Form
19     {
20         public Form1()
21         {
22             InitializeComponent();
23         }
24  
25         private void btnOpenXML_Click(object sender, EventArgs e)
26         {
27             // 1. 開啟 Excel 檔案,取得工作簿
28             using (SpreadsheetDocument document = SpreadsheetDocument.Open(@"C:\OpenXML.xlsx"true))
29             {
30                 WorkbookPart wbPart = document.WorkbookPart;
31  
32                 // 2. 取得工作簿中的工作表,並透過 Linq 判斷工作表是否存在
33                 Sheet theSheet = wbPart.Workbook.Descendants<Sheet>().
34                   Where(s => s.Name == "工作表1").FirstOrDefault();
35                 if (theSheet != null)
36                 {
37                     // 3. 建立 Cell 物件,設定寫入位置,格式,資料
38                     Cell cell = new Cell() { CellReference = "A1" };
39                     cell.DataType = new EnumValue<CellValues>(CellValues.String);
40                     cell.CellValue = new CellValue();
41                     cell.CellValue.Text = "點部落";
42  
43                     // 4. 建立 Row 物件,將 Cell 加入
44                     Row theRow = new Row();
45                     theRow.InsertAt(cell, 0);
46  
47                     // 5. 將 Row 加入工作表中
48                     Worksheet ws = ((WorksheetPart)(wbPart.GetPartById(theSheet.Id))).Worksheet;
49                     SheetData sheetData = ws.GetFirstChild<SheetData>();
50                     sheetData.Append(theRow);
51  
52                     // 6. 儲存檔案
53                     ws.Save();
54                 }
55             }
56         }
57     }
58 }

 

3. 執行結果

image

 

 

四、OpenOffice.org SDK

OpenOffice.org 是一套開放原始碼的辦公室軟體,其預設檔案格式為ISO標準開放格式(ODF,OpenDocument Format),使用 OpenOffice.org 也可以開啟與編輯 Microsoft Office 檔案格式,而 OpenOffice.org 有提供 OpenOffice.org SDK 讓我們可以對 OpenOffice.org 檔案與部分 Microsoft Office 檔案做操作。

目前 OpenOffice.org SDK 版本為 OpenOffice.org 3.2.0,假如要執行以 OpenOffice.org SDK 撰寫的程式,電腦必須先安裝 OpenOffice.org 才行。

1. OpenOffice.org SDK 下載與加入參考

(1) 連結到 The OpenOffice.org 3.2.0 Software Development Kit (SDK) 網頁進行下載

image

image

(2) 執行 OOo-SDK_3.2.0_Win32Intel_install_en-US.exe,會先進行解壓縮動作

image image

(3) 解壓縮完成後,開始進行安裝。

image image

image image

(4) 將 OpenOffice.org SDK 相關 dll 加入參考,資料夾位置在 C:\Program Files\OpenOffice.org_3.2_SDK\sdk\cli

image

image

 

2. 程式撰寫

請參考以下程式碼與註解,了解如何透過 OpenOffice.org SDK 寫入資料到 Excel 檔案,而使用 OpenOffice.org SDK 配合電腦有安裝 OpenOffice.org 可以做列印 Excel 檔案的動作。

01 using System;
02 using System.Collections.Generic;
03 using System.ComponentModel;
04 using System.Data;
05 using System.Drawing;
06 using System.Linq;
07 using System.Text;
08 using System.Windows.Forms;
09  
10 #region OpenOffice.org SDK
11 using unoidl.com.sun.star.lang;
12 using unoidl.com.sun.star.bridge;
13 using unoidl.com.sun.star.frame;
14 using unoidl.com.sun.star.view;
15 using unoidl.com.sun.star.beans;
16 using unoidl.com.sun.star.text;
17 using unoidl.com.sun.star.style;
18 using unoidl.com.sun.star.container;
19 #endregion  OpenOffice.org SDK
20  
21 namespace WinFormOpenOffice
22 {
23     public partial class Form1 : Form
24     {
25         public Form1()
26         {
27             InitializeComponent();
28         }
29  
30         private void btnOpenOffice_Click(object sender, EventArgs e)
31         {
32             #region 元件初始化
33             string sFileName = "C:\\OpenOffice.xlsx";
34  
35             unoidl.com.sun.star.uno.XComponentContext m_xContext;
36             unoidl.com.sun.star.lang.XMultiServiceFactory mxMSFactory;
37             unoidl.com.sun.star.sheet.XSpreadsheetDocument mxDocument;
38             unoidl.com.sun.star.container.XIndexAccess xSheetsIA;
39             unoidl.com.sun.star.sheet.XSpreadsheets xSheets;
40             unoidl.com.sun.star.sheet.XSpreadsheet xSheet;
41  
42             // OpenOffice.org 使用網址的方式,因此必須先將檔案路徑做轉換
43             String sUrl = "file:///" + sFileName.Replace(@"\", "/");
44  
45             // 載入文件前屬性設定,設定文件開啟時隱藏
46             PropertyValue[] loadDesc = new PropertyValue[1];
47             loadDesc[0] = new PropertyValue();
48             loadDesc[0].Name = "Hidden";
49             loadDesc[0].Value = new uno.Any(true);
50  
51             m_xContext = uno.util.Bootstrap.bootstrap();
52             mxMSFactory = (XMultiServiceFactory)m_xContext.getServiceManager();
53  
54             XComponentLoader aLoader = (XComponentLoader)mxMSFactory.createInstance("com.sun.star.frame.Desktop");
55  
56             // 載入文件
57             XComponent xComp = aLoader.loadComponentFromURL(sUrl, "_blank", 0, loadDesc);
58             mxDocument = (unoidl.com.sun.star.sheet.XSpreadsheetDocument)xComp;
59             xSheets = mxDocument.getSheets();
60             xSheetsIA = (unoidl.com.sun.star.container.XIndexAccess)xSheets;
61             xSheet = (unoidl.com.sun.star.sheet.XSpreadsheet)xSheetsIA.getByIndex(0).Value;
62             #endregion 元件初始化
63  
64             #region 寫入資料到 Excel
65             xSheet.getCellByPosition(1, 1).setFormula("點部落");
66             xSheet.getCellByPosition(1, 2).setFormula("小歐ou");
67             #endregion 寫入資料到 Excel
68  
69             #region 列印 Excel
70             PropertyValue[] printerProp = new PropertyValue[1];
71             printerProp[0] = new PropertyValue();
72             printerProp[0].Name = "Hide";
73             printerProp[0].Value = new uno.Any(true);
74  
75             XPrintable xPrintable = (XPrintable)xComp;
76             // 設定列印參數
77             xPrintable.setPrinter(printerProp);
78             printerProp = xPrintable.getPrinter();
79             PropertyValue[] printOps = new PropertyValue[1];
80             int indexOps = 0;
81             int iCopyNum = 1;  // 列印一份
82  
83             printOps[indexOps] = new PropertyValue();
84             printOps[indexOps].Name = "CopyCount";
85             printOps[indexOps].Value = new uno.Any(iCopyNum);
86  
87             xPrintable.print(printOps);
88             xComp.dispose();
89             #endregion 列印 Excel
90         }
91     }
92 }

 

3. 執行結果

image image

 

 

五、結語

本文看起來雖然簡短,但實際上花了好幾天時間去嘗試使用,點此可以下載範例

針對這三個函式庫有幾項心得 :

1. NPOI : 可操作 Excel 97-2003 格式 (.xls) 格式的 Excel 檔案,無法透過程式控制列印檔案。

2. OpenXML SDK : 可操作 Excel XML (.xlsx) 格式的 Excel 檔案,無法透過程式控制列印檔案。

3. OpenOffice.org SDK : 電腦需安裝 OpenOffice.org 才能使用,可以透過程式控制列印檔案。

而如何讓 NPOI 或 OpenXML SDK 編輯好的 Excel 檔案輸出到印表機做列印,請參考 [Office][C#]使用動態資料交換 (DDE) 將 EXCEL 檔案輸出至印表機進行列印

本文希望能夠對想要操作 Excel 的程式設計者有所幫助。

 

 

六、相關參考與連結

MSDN - Welcome to the Open XML SDK 2.0 for Microsoft Office

MSDN - 在 Server 端存取 Excel 檔案的利器:NPOI

OpenOffice.org - OpenOffice.org for Developers


收集自网络(地址:http://www.dotblogs.com.tw/chou/archive/2010/04/29/14912.aspx)

项目使用VS2017打开,.net 2.0下运行。 项目使用的微软官方的插件方法,可以将doc, docx, xls, xlsx, ppt, pptx文件转换为pdf文件,但是需要: 1、用户需要首先安装一个SaveAsPDFandXPS.exe的工具; 2、如果用户是xp系统,则: 2.1 如果用户安装的是office 2007,则用户在安装office 2007的时候必须要安装Visual Basic for Application 和 Microsoft Office Document Imaging这2个选项,否则转换失败; 2.2 如果用户安装的是office 2010,则在安装office 2010时必须要安装Visual Basic for Application选项,然后从office 2007安装包里面安装Microsoft Office Document Imaging(因为2010删除了这个选项,好麻烦~),否则转换失败; 2.3 xp不能安装office 2013/2016; 3、如果用户是win7系统,则: 3.1 如果用户安装的是office 2007,则用户在安装office 2007的时候必须要安装Visual Basic for Application 和 Microsoft Office Document Imaging这2个选项,否则转换失败; 3.2 如果用户安装的是office 2010,则在安装office 2010时必须要安装Visual Basic for Application选项(win7 + office 2010不需要安装Microsoft Office Document Imaging) 3.3 如果用户安装的是office 2013或2016,则不需要额外选项; 4、如果用户是win10系统,则: 4.1 如果用户安装的是office 2007,则用户在安装office 2007的时候必须要安装Visual Basic for Application这个选项,(win10 + office 2007不需要安装Microsoft Office Document Imaging)否则转换失败; 4.2 如果用户安装的是office 2010,则在安装office 2010时必须要安装Visual Basic for Application选项(win10 + office 2010不需要安装Microsoft Office Document Imaging) 4.3 如果用户安装的是office 2013或2016,则不需要额外选项; 5、如果用户安装了wps 2016或者wps 2019也可以正常转换。
C# NPOI是一个用于读取和写入Excel文件的开源库。它支持使用Open Office Xml格式(xlsx)进行操作。相比于EPPlus,NPOI不需要安装Office Excel,因此更加方便使用。 下面是一个使用C# NPOI读取和写入Excel文件的示例: 1. 首先,你需要在项目中添加NPOI的引用。你可以通过NuGet包管理器来添加NPOI引用。 2. 读取Excel文件: ```csharp using NPOI.SS.UserModel;using NPOI.XSSF.UserModel; using System.IO; // 读取Excel文件 string filePath = "path/to/your/excel/file.xlsx"; FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read); IWorkbook workbook = new XSSFWorkbook(file); ISheet sheet = workbook.GetSheetAt(0); // 遍历行和列 for (int row = 0; row <= sheet.LastRowNum; row++) { IRow currentRow = sheet.GetRow(row); if (currentRow != null) { for (int col = 0; col < currentRow.LastCellNum; col++) { ICell cell = currentRow.GetCell(col); if (cell != null) { string cellValue = cell.ToString(); // 处理单元格的值 // ... } } } } file.Close(); ``` 3. 写入Excel文件: ```csharp using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System.IO; // 创建Excel工作簿 IWorkbook workbook = new XSSFWorkbook(); ISheet sheet = workbook.CreateSheet("Sheet1"); // 写入数据 for (int row = 0; row < data.Length; row++) { IRow currentRow = sheet.CreateRow(row); for (int col = 0; col < data[row].Length; col++) { ICell cell = currentRow.CreateCell(col); cell.SetCellValue(data[row][col]); } } // 保存Excel文件 string filePath = "path/to/save/excel/file.xlsx"; FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write); workbook.Write(file); file.Close(); ``` 请注意,上述示例中的"data"是一个二维数组,用于存储要写入Excel文件的数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值