[Office][C#] NPOI、OpenXML SDK、OpenOffice.org SDK 写入资料到 EXCEL 档案[转]
原文地址:http://www.dotblogs.com.tw/chou/archive/2010/04/29/14912.aspx
一、簡介
要將資料寫入 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 加入參考中。
![]()
2. 程式撰寫
請參考以下程式碼與註解,了解如何透過 NPOI 寫入資料到 Excel 檔案,以下程式為建立工作簿、工作表、寫入資料、儲存檔案。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms; using System.IO; #region NPOI
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
#endregion NPOI namespace WinFormNPOI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void btnNPOI_Click(object sender, EventArgs e)
{
// 建立新的 Excel 工作簿
HSSFWorkbook hssfworkbook = new HSSFWorkbook(); // 在 Excel 工作簿中建立工作表,名稱為 Sheet1
HSSFSheet sheet1 = hssfworkbook.CreateSheet("Sheet1"); // 寫入資料到工作表中
sheet1.CreateRow().CreateCell().SetCellValue("點部落");
sheet1.CreateRow().CreateCell().SetCellValue("小歐ou"); // 儲存檔案
FileStream file = new FileStream(@"C:\NPOI.xls", FileMode.Create);
hssfworkbook.Write(file);
file.Close();
}
}
}
3. 執行結果
![]()
三、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 進行下載
![]()
![]()
(2) 執行 OpenXMLSDKv2.msi 進行安裝,安裝過程並沒有特別的過程,只是要記得安裝路徑在哪,免得找不到 dll。
![]()
![]()
![]()
(3) 將 DocumentFormat.OpenXml.dll、WindowsBase.dll 加入參考
DocumentFormat.OpenXml.dll 位置在 C:\Program Files\Open XML SDK\V2.0\lib\DocumentFormat.OpenXml.dll
![]()
![]()
2. 程式撰寫
參考程式碼與註解說明,程式流程如下
(1) 開啟 Excel 檔案,取得工作簿
(2) 取得工作簿中的工作表,並透過 Linq 判斷工作表是否存在
(3) 建立 Cell 物件,設定寫入位置,格式,資料
(4) 建立 Row 物件,將 Cell 加入
(5) 將 Row 加入工作表中
(6) 儲存檔案
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms; #region OpenXML SDK
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
#endregion OpenXML SDK namespace WinFormOpenXML
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void btnOpenXML_Click(object sender, EventArgs e)
{
// 1. 開啟 Excel 檔案,取得工作簿
using (SpreadsheetDocument document = SpreadsheetDocument.Open(@"C:\OpenXML.xlsx", true))
{
WorkbookPart wbPart = document.WorkbookPart; // 2. 取得工作簿中的工作表,並透過 Linq 判斷工作表是否存在
Sheet theSheet = wbPart.Workbook.Descendants<Sheet>().
Where(s => s.Name == "工作表1").FirstOrDefault();
if (theSheet != null)
{
// 3. 建立 Cell 物件,設定寫入位置,格式,資料
Cell cell = new Cell() { CellReference = "A1" };
cell.DataType = new EnumValue<CellValues>(CellValues.String);
cell.CellValue = new CellValue();
cell.CellValue.Text = "點部落"; // 4. 建立 Row 物件,將 Cell 加入
Row theRow = new Row();
theRow.InsertAt(cell, ); // 5. 將 Row 加入工作表中
Worksheet ws = ((WorksheetPart)(wbPart.GetPartById(theSheet.Id))).Worksheet;
SheetData sheetData = ws.GetFirstChild<SheetData>();
sheetData.Append(theRow); // 6. 儲存檔案
ws.Save();
}
}
}
}
}
3. 執行結果
![]()
四、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) 網頁進行下載
![]()
![]()
(2) 執行 OOo-SDK_3.2.0_Win32Intel_install_en-US.exe,會先進行解壓縮動作
![]()
(3) 解壓縮完成後,開始進行安裝。
![]()
![]()
(4) 將 OpenOffice.org SDK 相關 dll 加入參考,資料夾位置在 C:\Program Files\OpenOffice.org_3.2_SDK\sdk\cli
![]()
![]()
2. 程式撰寫
請參考以下程式碼與註解,了解如何透過 OpenOffice.org SDK 寫入資料到 Excel 檔案,而使用 OpenOffice.org SDK 配合電腦有安裝 OpenOffice.org 可以做列印 Excel 檔案的動作。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms; #region OpenOffice.org SDK
using unoidl.com.sun.star.lang;
using unoidl.com.sun.star.bridge;
using unoidl.com.sun.star.frame;
using unoidl.com.sun.star.view;
using unoidl.com.sun.star.beans;
using unoidl.com.sun.star.text;
using unoidl.com.sun.star.style;
using unoidl.com.sun.star.container;
#endregion OpenOffice.org SDK namespace WinFormOpenOffice
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void btnOpenOffice_Click(object sender, EventArgs e)
{
#region 元件初始化
string sFileName = "C:\\OpenOffice.xlsx"; unoidl.com.sun.star.uno.XComponentContext m_xContext;
unoidl.com.sun.star.lang.XMultiServiceFactory mxMSFactory;
unoidl.com.sun.star.sheet.XSpreadsheetDocument mxDocument;
unoidl.com.sun.star.container.XIndexAccess xSheetsIA;
unoidl.com.sun.star.sheet.XSpreadsheets xSheets;
unoidl.com.sun.star.sheet.XSpreadsheet xSheet; // OpenOffice.org 使用網址的方式,因此必須先將檔案路徑做轉換
String sUrl = "file:///" + sFileName.Replace(@"\", "/"); // 載入文件前屬性設定,設定文件開啟時隱藏
PropertyValue[] loadDesc = new PropertyValue[];
loadDesc[] = new PropertyValue();
loadDesc[].Name = "Hidden";
loadDesc[].Value = new uno.Any(true); m_xContext = uno.util.Bootstrap.bootstrap();
mxMSFactory = (XMultiServiceFactory)m_xContext.getServiceManager(); XComponentLoader aLoader = (XComponentLoader)mxMSFactory.createInstance("com.sun.star.frame.Desktop"); // 載入文件
XComponent xComp = aLoader.loadComponentFromURL(sUrl, "_blank", , loadDesc);
mxDocument = (unoidl.com.sun.star.sheet.XSpreadsheetDocument)xComp;
xSheets = mxDocument.getSheets();
xSheetsIA = (unoidl.com.sun.star.container.XIndexAccess)xSheets;
xSheet = (unoidl.com.sun.star.sheet.XSpreadsheet)xSheetsIA.getByIndex().Value;
#endregion 元件初始化 #region 寫入資料到 Excel
xSheet.getCellByPosition(, ).setFormula("點部落");
xSheet.getCellByPosition(, ).setFormula("小歐ou");
#endregion 寫入資料到 Excel #region 列印 Excel
PropertyValue[] printerProp = new PropertyValue[];
printerProp[] = new PropertyValue();
printerProp[].Name = "Hide";
printerProp[].Value = new uno.Any(true); XPrintable xPrintable = (XPrintable)xComp;
// 設定列印參數
xPrintable.setPrinter(printerProp);
printerProp = xPrintable.getPrinter();
PropertyValue[] printOps = new PropertyValue[];
int indexOps = ;
int iCopyNum = ; // 列印一份 printOps[indexOps] = new PropertyValue();
printOps[indexOps].Name = "CopyCount";
printOps[indexOps].Value = new uno.Any(iCopyNum); xPrintable.print(printOps);
xComp.dispose();
#endregion 列印 Excel
}
}
}
3. 執行結果
![]()
五、結語
本文看起來雖然簡短,但實際上花了好幾天時間去嘗試使用,點此可以下載範例。
針對這三個函式庫有幾項心得 :
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
[Office][C#] NPOI、OpenXML SDK、OpenOffice.org SDK 写入资料到 EXCEL 档案[转]的更多相关文章
- SDK接入(U8SDK)——SDK抽象层的设计
上一篇文章,我们总体地分析并设计了一套高效的SDK接入方案,也罗列出这套方案,我们需要完成的工作.这里再罗列并回顾下: 1.统一抽象的SDK接入框架 2.各个SDK接入实现 3.一键打包工具 4.统一 ...
- Platform SDK、Windows SDK简介
Platform SDK及Windows SDK是由微软公司出品的一个软件开发包,向在微软的Windows操作系统和.NET框架上开发软件和网站的程序员提供头文件.库文件.示例代码.开发文档和开发工具 ...
- 修改Intellij IDEA中工程对应的Java SDK、Scala SDK
如果编译Scala工程时,遇到如下异常: can't expand macros compiled by previous versions of Scala 很可能是工程的scala版本,和依赖的包 ...
- Android sdk platform,sdk tools,sdk Build tools,sdk platform tools 的关系
1. sdk platform 简单理解为系统版本 最新级别: 28:Android 9 27:Android 8.1 26:Android 8.0 25:Android 7.1 24:Android ...
- 关于DirectShow SDK 和Windows SDK,及DirectX SDK
关于DirectShow SDK 和Windows SDK,及DirectX SDK 本文描述了DirectShow SDK ,Windows SDK,DirectX SDK ,VS200?之间的 ...
- ESP8266 NON-OS SDK 和 RTOS SDK实现GPIO中断不同点
ESP8266 Non-OS SDK 和 RTOS SDK 实现GPIO的方法稍有不同: 对于 Non-OS SDK,比如需要把 MTDO 配置成输入,同时下降沿触发中断: gpio_init(voi ...
- [转]关于sdk更新Android SDK Tools 25.3.1版本后使用sdk manager闪退
昨天这两个manager还工作正常,今天更新了一下,发现不可用了,运行avd manager和sdk manager没反应,搜了好多文章,然后看到了下这篇文章<关于sdk更新Android SD ...
- Android SDK Manager 下载SDK失败的解决办法
摘要:本文记录了无法使用Android SDK Manager下载SDK开发包的解决办法. 最近需要进行android应用程序的开发工作,在android官网下载了adt-bundle-linux- ...
- NPOI利用多任务模式分批写入多个Excel
接上文NPOI大数据分批写入同个Excel,这次是利用task多任务同时写入到多个Excel. Form2.cs private void btnExport_Click(object sender, ...
随机推荐
- SilverlightERP&CRM源码(可用于开发基于Silverlight的CRM,OA,HR,进销存等)
SilverlightERP系统源代码(支持创建OA.SilverlightCRM.HR.进销存.财务等系统之用) 可用于开发以下系统 SilverlightERP SilverlightCRM Si ...
- javascript性能优化总结一(转载人家)
一直在学习javascript,也有看过<犀利开发Jquery内核详解与实践>,对这本书的评价只有两个字犀利,可能是对javascript理解的还不够透彻异或是自己太笨,更多的是自己不擅于 ...
- itextSharp 附pdf文件解析
一.PdfObject: pdf对象 ,有9种,对象是按照对象内涵来分的,如果按照对象的使用规则来说,对象又分为间接对象和直接对象.间接对象是PDF中最常用的对象,如前面对象集合里面的,所有对象都是间 ...
- sql语句,怎么查看一个表中的所有约束
sql语句,怎么查看一个表中的所有约束,比如,一个student表,有唯一,外键,主键,用sql语句怎么查看student表中的所有约束呢? select * from sysobjects wher ...
- less笔记
koala工具 注释: 1./**/,可以被编译 2.//,不可以被编译 申明变量: @box_width:300px; .box{ width:@box_wid ...
- HDU5878
http://acm.hdu.edu.cn/showproblem.php?pid=5878 给出你一个数字,让你求出大于这个数字n并且是形如2^a*3^b*5^c*7^d的最小的数: 就是用打表法求 ...
- C# 正则表达式及返回匹配的所有结果
C# 正则表达式是在 System.Text.RegularExpressions 空间定义的,其中的 IsMatch() 方法用于返回 bool 类型,表示要搜索的字符串与传入的正则表达式是否匹配 ...
- windows8.1+centos7双系统(装完centos后无win8引导)
原先系统为windows8.1后来装上centos7后无win8系统引导, 打开电脑进入引导界面按C 进入grub界面 输入“cat (hd0,” 按tab可查看到windows8 地址为“hd0, ...
- 如何用js刷新aspxgridviw
//写在js中 ASPxGridView1.Refresh();
- C# RSA 算法
RSA公钥加密算法是1977年由Ron Rivest.Adi Shamirh和LenAdleman在(美国麻省理工学院)开发的.RSA取名来自开发他们三者的名字.RSA是目前最有影响力的公钥加密算法, ...