原文地址: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 档案[转]的更多相关文章

  1. SDK接入(U8SDK)——SDK抽象层的设计

    上一篇文章,我们总体地分析并设计了一套高效的SDK接入方案,也罗列出这套方案,我们需要完成的工作.这里再罗列并回顾下: 1.统一抽象的SDK接入框架 2.各个SDK接入实现 3.一键打包工具 4.统一 ...

  2. Platform SDK、Windows SDK简介

    Platform SDK及Windows SDK是由微软公司出品的一个软件开发包,向在微软的Windows操作系统和.NET框架上开发软件和网站的程序员提供头文件.库文件.示例代码.开发文档和开发工具 ...

  3. 修改Intellij IDEA中工程对应的Java SDK、Scala SDK

    如果编译Scala工程时,遇到如下异常: can't expand macros compiled by previous versions of Scala 很可能是工程的scala版本,和依赖的包 ...

  4. 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 ...

  5. 关于DirectShow SDK 和Windows SDK,及DirectX SDK

    关于DirectShow SDK 和Windows SDK,及DirectX SDK   本文描述了DirectShow SDK ,Windows SDK,DirectX SDK ,VS200?之间的 ...

  6. ESP8266 NON-OS SDK 和 RTOS SDK实现GPIO中断不同点

    ESP8266 Non-OS SDK 和 RTOS SDK 实现GPIO的方法稍有不同: 对于 Non-OS SDK,比如需要把 MTDO 配置成输入,同时下降沿触发中断: gpio_init(voi ...

  7. [转]关于sdk更新Android SDK Tools 25.3.1版本后使用sdk manager闪退

    昨天这两个manager还工作正常,今天更新了一下,发现不可用了,运行avd manager和sdk manager没反应,搜了好多文章,然后看到了下这篇文章<关于sdk更新Android SD ...

  8. Android SDK Manager 下载SDK失败的解决办法

    摘要:本文记录了无法使用Android SDK  Manager下载SDK开发包的解决办法. 最近需要进行android应用程序的开发工作,在android官网下载了adt-bundle-linux- ...

  9. NPOI利用多任务模式分批写入多个Excel

    接上文NPOI大数据分批写入同个Excel,这次是利用task多任务同时写入到多个Excel. Form2.cs private void btnExport_Click(object sender, ...

随机推荐

  1. gauss消元

    题意描述:有n个星球,m台望远镜.每台望远镜有一个开始时间和结束时间,但只给出了月.日的信息,没有给出年份,每台望远镜记录了它所观测的星球上发生的各类事件的次数.每类事件持续的时间是恒定的,且不会超过 ...

  2. Maven依赖排除 禁止依赖传递 取消依赖的方法

    大家都知道Maven的优点是依赖管理,特别是前期使用ANT的开发者都有很多感触.最近要开发一个java工程,定的要使用maven,会使用hadoop和hbase的客户端,而引入一个hadoop-cli ...

  3. Mobile Web调试工具Weinre (reproduce)

    Mobile Web调试工具Weinre 现在.将来,用移动设备上网越来越成为主流.但对于开发者们来说,移动web的调试一直是个难题,前期可以使用模拟器来协助调试,但到了真机调试阶段就让人非常头痛.而 ...

  4. KVO/KVC 实现机理分析

    来源:http://blog.csdn.net/dqjyong/article/details/7672865 Objective-C里面的Key-Value Observing (KVO)机制,非常 ...

  5. [CF442B] Andrey and Problem (概率dp)

    题目链接:http://codeforces.com/problemset/problem/442/B 题目大意:有n个人,第i个人出一道题的概率是pi,现在选出一个子集,使得这些人恰好出一个题的概率 ...

  6. Blackfin DSP(八):BF533的DMA

    #include <cdefBF533.h> #include <sys\exception.h> #define POLC 0x00004000 #define PORT_C ...

  7. 68. Longest Common Prefix

    Longest Common Prefix Write a function to find the longest common prefix string amongst an array of ...

  8. FreeBSD 10 中文环境

    中文字体位置 FontPath        "/usr/local/lib/X11/fonts/misc/:unscaled" FontPath        "/us ...

  9. Monty Hall Problem的一个图解,感觉不错

    从Coursera.org上的台大概率课讨论组里拿来的 如果不转换,选中汽车的概率是1/3,非常显然. 但转换后选中汽车的概率变成2/3就有点反直觉了,并不是太容易想明白. 因为转换其实有4种:汽车- ...

  10. Spark SQL External Data Sources JDBC简易实现

    在spark1.2版本中最令我期待的功能是External Data Sources,通过该API可以直接将External Data Sources注册成一个临时表,该表可以和已经存在的表等通过sq ...