顯示具有 匯出 標籤的文章。 顯示所有文章
顯示具有 匯出 標籤的文章。 顯示所有文章

2025年3月31日 星期一

[研究]ASP.NET 使用 NPOI 匯出寫入 Excel (.xlsx) 檔案

[研究]ASP.NET 使用 NPOI 匯出寫入 Excel (.xlsx) 檔案

[研究]ASP.NET 把 ClosedXML 匯出寫入改寫為使用 NPOI 匯出寫入 Excel (.xlsx) 檔案

2025-03-31

環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C# + SQL Server 2019 + SQL Server Management Studio (SSMS) 19

********************************************************************************

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
    Inherits="WebApplication1.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Button ID="Button_Export_Xlsx_by_ClosedXML" runat="server"
            OnClick="Button_Export_Xlsx_by_ClosedXML_Click" Text="匯出(ClosedXML)"
            CssClass="btn btn-info btn-xs" /><br />
        <asp:Button ID="Button_Export_Xlsx_by_NPOI" runat="server"
            OnClick="Button_Export_Xlsx_by_NPOI_Click" Text="匯出(NPOI)"
            CssClass="btn btn-info btn-xs" /><br />
        <asp:Label ID="Label_MSG1" runat="server"></asp:Label>
        <br />
    </form>
</body>
</html>


Default.aspx.cs

using ClosedXML.Excel;
using System;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;

using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        // 匯出查詢結果(.xlsx)
        #region == protected void Button_Export_Xlsx_by_ClosedXML_Click(object sender, EventArgs e) ==
        protected void Button_Export_Xlsx_by_ClosedXML_Click(object sender, EventArgs e)
        {
            //string mainFileName = "匯出檔案名稱";
            string mainFileName = "匯出";
            string fd = (string)ConfigurationManager.AppSettings["TempFolder"] + Path.DirectorySeparatorChar.ToString();
            string dateTimeString = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-fff");
            // 若檔案名稱有中文字或特殊符號,Response.AddHeader() 輸出檔案名稱要編碼
            string outFileName = HttpUtility.UrlEncode(
                mainFileName, System.Text.Encoding.UTF8) + "-" +
                dateTimeString + ".xlsx";

            // XLWorkbook.SaveAs() 輸出檔案名稱不要用 HttpUtility.UrlEncode 編碼
            // Response.TransmitFile() 輸出檔案名稱不要用 HttpUtility.UrlEncode 編碼
            string dirFileName = fd + mainFileName + "-" +
                dateTimeString + ".xlsx";
            try
            {
                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "";

                #region === Export ===

                // [EXCEL] Excel打開是亂碼?快速找回資料的最好方法!
                // http://blog.e-happy.com.tw/excel-excel%E6%89%93%E9%96%8B%E6%98%AF%E4%BA%82%E7%A2%BC%EF%BC%9F%E5%BF%AB%E9%80%9F%E6%89%BE%E5%9B%9E%E8%B3%87%E6%96%99%E7%9A%84%E6%9C%80%E5%A5%BD%E6%96%B9%E6%B3%95%EF%BC%81/

                // Excel開啟CSV時的中文編碼問題補遺
                //https://blog.darkthread.net/blog/csv-encoding-again/

                //Response.ContentType = "application/vnd.oasis.opendocument.spreadsheet";    // ODF/.ods
                //Response.AddHeader("content-disposition", "attachment;filename=" + outFileName);
                using (MemoryStream myMemoryStream = new MemoryStream())
                {


                    string dataText = "";

                    var wb = new XLWorkbook();
                    var ws = wb.Worksheets.Add("工作表1");

                    // 定義欄位名稱列
                    string[] columnNameArray = { "欄位1", "欄位2", "欄位3" };
                    // Column number must be between 1 and 16384
                    for (int i = 0; i < columnNameArray.Count(); i++)
                    {
                        ws.Cell(1, i + 1).Value = columnNameArray[i];
                    }

                    // 讀取資料,資料寫入「工作表1」
                    //                    string queryString = @"
                    //--DECLARE  @FieldText nvarchar(50)
                    //--SET @FieldText=N'abc'

                    //SELECT * FROM [TestDB].[dbo].[Table1]
                    //";

                    //string queryString = SqlDataSource1.SelectCommand;
                    string queryString = @"SELECT * FROM [MyDB].[dbo].[MyTable]";

                    //queryString = SqlDataSource1.SelectCommand;
                    using (SqlConnection connection = new SqlConnection(
                        WebConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString))
                    {
                        SqlCommand command = new SqlCommand(queryString, connection);
                        connection.Open();
                        using (SqlDataReader reader = command.ExecuteReader())
                        {
                            int rowIndex = 1;   // 1 是標題列
                            while (reader.Read())
                            {
                                rowIndex++;
                                for (int i = 0; i < reader.FieldCount; i++)
                                {
                                    //reader[i]的 i 要從 0 開始
                                    dataText = reader[i].ToString();

                                    // 規則運算式語言 - 快速參考 | Microsoft Docs
                                    // https://docs.microsoft.com/zh-tw/dotnet/standard/base-types/regular-expression-language-quick-reference

                                    // 換掉特殊字元 (自己評估)
                                    dataText = dataText.Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace(",", ",").Replace("'", "′").Replace(@"""", "”");
                                    dataText = dataText.Replace("\a", "").Replace("\b", "").Replace("\t", "").Replace("\v", "").Replace("\f", "").Replace("\\", "");

                                    // Column number must be between 1 and 16384
                                    ws.Cell(rowIndex, i + 1).Value = dataText;
                                }
                            }
                        }

                        Response.Clear();
                        Response.Buffer = true;
                        Response.ContentEncoding = Encoding.GetEncoding(950);   //950就是所謂的BIG5
                                                                                //Response.AddHeader("Content-Disposition", "attachment;filename=\"" +
                                                                                //    HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + "-" +
                                                                                //    DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx");
                        Response.AddHeader("Content-Disposition", "attachment;filename=\"" + outFileName);
                        //'Excel 2003 : "application/vnd.ms-excel"
                        //'Excel 2007 : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

                        //Extension       MIME Type
                        //.xlsx               application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
                        //.xltx                application/vnd.openxmlformats-officedocument.spreadsheetml.template
                        //.potx               application/vnd.openxmlformats-officedocument.presentationml.template
                        //.ppsx              application/vnd.openxmlformats-officedocument.presentationml.slideshow
                        //.pptx               application/vnd.openxmlformats-officedocument.presentationml.presentation
                        //.sldx               application/vnd.openxmlformats-officedocument.presentationml.slide
                        //.docx              application/vnd.openxmlformats-officedocument.wordprocessingml.document
                        //.dotx               application/vnd.openxmlformats-officedocument.wordprocessingml.template
                        //.xlam              application/vnd.ms-excel.addin.macroEnabled.12
                        //.xlsb               application/vnd.ms-excel.sheet.binary.macroEnabled.12

                        //Response.ContentType = "application/ms-excel";
                        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

                        //Response.TransmitFile(@"C:\Program Files (x86)\IIS Express\Export.xlsx");
                        //dirFileName = dirFileName.Replace('\\', '/');   //轉換 Windows, Linux 不同路徑斜線
                        //dirFileName = dirFileName.Replace("/", "\\");  // 轉換斜線 / 成 \  ,因 \ 是特殊符號,要以 \\ 表示

                        // 方法1: 直接輸出
                        wb.SaveAs(myMemoryStream);
                        Response.BinaryWrite(myMemoryStream.ToArray());
                        // myMemoryStream.WriteTo(Response.OutputStream); //works too
                        Response.Flush();
                        Response.Close();

                        // 方法2: 若需要寫入檔案再輸出
                        wb.SaveAs(dirFileName);                 // 存檔,Debug 或其他用途
                                                                ////Response.WriteFile(savePath);
                                                                //Response.TransmitFile(dirFileName);   // 把存檔輸出

                        // 輸出結束
                        Response.End();

                        Label_MSG1.ForeColor = System.Drawing.Color.Green;
                        Label_MSG1.Text = "匯出成功。";
                        // 上面 Response 輸出檔案,所以下面 JavaScript alert 是不會跳出的
                        //Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('匯出成功。');</script>");
                    }
                }
                #endregion Export ODS
            }
            catch (Exception)
            {
                throw;
            }
        }
        #endregion

        // 匯出查詢結果(.xlsx)
        #region == protected void Button_Export_Xlsx_by_NPOI_Click(object sender, EventArgs e) ==
        protected void Button_Export_Xlsx_by_NPOI_Click(object sender, EventArgs e)
        {
            string mainFileName = "匯出";
            string dateTimeString = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-fff");
            string outFileName = HttpUtility.UrlEncode(mainFileName, System.Text.Encoding.UTF8) + "-" + dateTimeString + ".xlsx";

            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    IWorkbook workbook = new XSSFWorkbook();  // 使用 XSSFWorkbook (XLSX 格式)
                    ISheet sheet = workbook.CreateSheet("工作表1");

                    // 設定標題列
                    string[] columnNames = { "欄位1", "欄位2", "欄位3" };
                    IRow headerRow = sheet.CreateRow(0);
                    for (int i = 0; i < columnNames.Length; i++)
                    {
                        headerRow.CreateCell(i).SetCellValue(columnNames[i]);
                    }

                    // 讀取資料
                    string queryString = @"SELECT * FROM [MyDB].[dbo].[MyTable]";
                    using (SqlConnection connection = new SqlConnection(
                        WebConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString))
                    {
                        SqlCommand command = new SqlCommand(queryString, connection);
                        connection.Open();
                        using (SqlDataReader reader = command.ExecuteReader())
                        {
                            int rowIndex = 1;
                            while (reader.Read())
                            {
                                IRow row = sheet.CreateRow(rowIndex++);
                                for (int i = 0; i < reader.FieldCount; i++)
                                {
                                    string dataText = reader[i].ToString()
                                        .Replace("\r", "").Replace("\n", "").Replace("\t", "")
                                        .Replace(",", ",").Replace("'", "′").Replace("\"", "”")
                                        .Replace("\\", "").Replace("\a", "").Replace("\b", "")
                                        .Replace("\v", "").Replace("\f", "");

                                    row.CreateCell(i).SetCellValue(dataText);
                                }
                            }
                        }
                    }

                    // **避免 MemoryStream 被 NPOI 關閉**
                    workbook.Write(ms);
                    ms.Flush();

                    // 設定 Response 參數
                    Response.Clear();
                    Response.Buffer = true;
                    Response.ContentEncoding = Encoding.UTF8;
                    Response.AddHeader("Content-Disposition", "attachment;filename=\"" + outFileName + "\"");
                    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

                    // 輸出檔案
                    Response.BinaryWrite(ms.ToArray());
                    Response.Flush();
                    Response.End();
                }
            }
            catch (Exception ex)
            {
                Label_MSG1.ForeColor = System.Drawing.Color.Red;
                Label_MSG1.Text = "匯出失敗:" + ex.Message;
            }
        }


        #endregion
    }
}

敝人實際20萬筆測試速度,有時ClosedXML快,有時 NPOI快。

(完)

相關

2021年2月18日 星期四

[研究][ASP.NET]讀取、匯出、寫入、匯入 Excel .xlsx .xls ODF .ods

[研究][ASP.NET]讀取、匯出、寫入、匯入 Excel .xlsx .xls ODF .ods

2020-04-09、2020-04-17、2020-04-28、2021-02-18、2023-01-15 更新

Visual Studio + ASP.NET + WebForm + C#

微軟官方並不建議在伺服器端使用直接存取 Excel 物件模型的方式來控制 Excel 檔案,除了上述的資源無法釋放的問題外,還有像是權限的問題,以及安全性問題等等,詳細的資料請參考:

Considerations for server-side Automation of Office - Microsoft Support
http://support.microsoft.com/default.aspx/kb/257757

在 Server 端控制 Excel 的難處 | Microsoft Learn
2014/06/12

Office 伺服器端自動化的考量因素 - Microsoft Support
https://support.microsoft.com/zh-tw/help/257757/considerations-for-server-side-automation-of-office

Considerations for server-side Automation of Office
https://support.microsoft.com/fi-fi/help/257757/considerations-for-server-side-automation-of-office

Excel 與舊版 Excel 搭配使用
Excel 97-2003 支援256欄寬、65536列高,超出此欄和列限制的儲存格資料將會遺失。
Excel 2007 開始,工作表大小是1048576列高。

Excel 的規格及限制 - Microsoft 365 Excel, Excel 2019, Excel 2016, Excel 2013, Excel 2010, Excel 2007

(下圖)實際測試 Excel 2016,超過 256 欄位資料儲存成 .xls 時候,會有警告。
65536列的限制在 .xls 檔案,不管 Excel 是甚麼版本。



********************************************************************************

匯出、寫入Excel (.xlsx) 

注意元件更新狀況,多年未更新或停止研發的建議別用。

[研究][ASP.NET]使用 OpenXML 2.12.2 匯出、寫入 .xlsx

[研究][ASP.NET]使用 ClosedXML 0.95.4 匯出、寫入 .xlsx

[研究][ASP.NET]使用 Aspose.Cells 21.2.0 匯出、寫入 .ods 或 .xlsx

[研究][C#][ASP.NET][WebForm] 用 ClosedXML 0.95.0 把 GridView1 匯出成 Excel (.xlsx)
https://shaurong.blogspot.com/2020/04/caspnetwebform-closedxml-0950-gridview1.html
ClosedXML 需要 Microsoft OpenXML SDK ( NuGet 上稱為 DocumentFormat.OpenXml )

[研究][C#][ASP.NET][WebForm] 使用 Microsoft OpenXML 2.10.1 (DocumentFormat.OpenXml) 把 GridView 匯出成 .xlsx
https://shaurong.blogspot.com/2020/04/caspnetwebform-openxml-2101.html

[研究][C#][ASP.NET] GridView 匯出成 Excel (.xlsx) (使用 Microsoft OpenXML SDK 2.5)
http://shaurong.blogspot.tw/2016/03/caspnet-gridview-excel-xlsx-openxml-sdk.html

[研究] [C#] 用 ClosedXML 在 Server端操作 Excel,安裝與試用 (NuGet安裝)
http://shaurong.blogspot.com/2017/11/c-closedxml-server-excel-nuget.html

EPPLus 待測
https://www.nuget.org/packages/EPPlus/
目前最新為  2020-04-07 的 v5.1.0 版
From version 5 EPPlus changes the licence model using a dual license, Polyform Non Commercial / Commercial license.

SpreadSheetLight 待測
https://www.nuget.org/packages/SpreadsheetLight/
http://spreadsheetlight.com/
目前最新 2020年11月的 3.5.0 版 ( 目前2021/02/09 )
需要 OpenXMLSDK 2.5

ExcelPackage 1.0.0
最後釋出 2015年5月22日 (2015/5/22),目前2021/02/09,已經多年未更新。

public static void WriteToExcel(string[] newInfoArray)
        {
            FileInfo fileInfo = new FileInfo(pathName);

            using (ExcelPackage packge = new ExcelPackage(fileInfo))
            {
                ExcelWorksheet worksheet = packge.Workbook.Worksheets[sheetName];

                for (int i = 0; i < newInfoArray.Length; ++i)
                {
                    worksheet.Cells[selectIndex + 2, i + 1].Value = newInfoArray[i];
                }

                packge.Save();
            }
        }
********************************************************************************

Excel (.xlsx) 匯出、匯入 注意事項

目前拿來匯入的 .xlsx 檔案,若為直接用 Microsoft Excel 建立的,不會有問題。用任何元件匯出產生的 .xlsx,不保證匯入成功;就算此時再拿 Microsoft Excel 另存過一次也不保證匯入成功。

而用任何元件產生的 .xlsx 檔案,用 Microsoft Excel 開啟,也不保證 100% 成功。

有可能是元件本身相容性問題 or Bug or 程式寫法問題。


[研究][C#][ASP.NET][WebForm] ClosedXML 匯入錯誤:參數名稱: The range 工作表1!A1:L2 is already part of table 'Table1'
https://shaurong.blogspot.com/2020/04/closedxml-range-1a1l2-is-already-part.html

********************************************************************************

匯入、讀取Excel (.xlsx) 


[研究][ASP.NET]使用 OpenXML SDK 2.12.1 讀取匯入 .xlsx 到資料庫
DocumentFormat.OpenXml 2.12.1

[研究][ASP.NET]使用 ClosedXML 0.95.4 讀取匯入 .xlsx 到資料庫

[研究][ASP.NET]使用 Aspose.Cells 21.1.0 讀取匯入 .xlsx 或 .ods 到資料庫

[研究][ASP.NET] 用 ExcelDataReader 讀取匯入 .xlsx , .xls , csv 檔案到 GridView1
https://shaurong.blogspot.com/2020/04/caspnetwebform-exceldatareader-xlsx-xls.html
Web Server 不需安裝 Office,目前最新為 2019/5/2 的 v3.6.0,支援 .csv, .xls, .xlsx 讀取,不支援寫入

[研究][ASP.NET]使用 NPOI 2.5.2 讀取匯入 .xlsx 到資料庫

[研究][ASP.NET]使用 ExcelDataReader 3.6.0 讀取匯入 .xlsx 到資料庫
https://shaurong.blogspot.com/2021/02/aspnet-exceldatareader-360-xlsx.html

[研究] [C#] [WinForm] 取得 Excel 的所有 工作表 名稱,及儲存格內容 (使用Access Database Engine 2010)
http://shaurong.blogspot.tw/2016/11/c-winform-excel.html

[研究] Excel 2016 (.xlsx) 匯入 SQL Server 2019
https://shaurong.blogspot.com/2019/12/excel-2016-xlsx-sql-server-2019.html

********************************************************************************

匯出 Excel (.xls)


[研究][C#][ASP.NET][WebForm] 使用 Microsoft OpenXML SDK 2.10.1 ( DocumentFormat.OpenXml ) 把 Excel .xlsx 匯入
https://shaurong.blogspot.com/2020/04/caspnetwebform-microsoft-openxml-sdk.html

[研究][C#][ASP.NET] GridView 匯出成 .xls (使用 Excel)
http://shaurong.blogspot.tw/2016/03/caspnet-gridview-xls-excel.html
電腦要安裝 Office 軟體

[研究][ASP.NET][C#]使用 NPOI 的 RenderDataTableToExcel 匯出資料成 Excel (.xls) 檔案
待測
Server電腦要不安裝 Office 軟體,NOPI 支援 xls, xlsx, docx.

[研究][C#][ASP.NET] 用 NPOI v2.2.1 在 Server 端存取 Excel 檔案 (從官方下載安裝)
http://shaurong.blogspot.com/2017/11/caspnet-npoi-v221-server-excel.html
NOPI 支援 xls, xlsx, docx.

[研究][C#][ASP.NET] 用 NPOI v2.3.0 在 Server 端存取 Excel 檔案 (NuGet安裝)
http://shaurong.blogspot.com/2017/11/caspnet-npoi-server-excel-nuget.html

[研究][C#][ASP.NET] GridView 匯出成 Excel (.xls)(以Html方式輸出)
http://shaurong.blogspot.tw/2016/03/caspnet-gridview-excel-xlshtml.html

EPPlus
https://github.com/JanKallman/EPPlus
EPPlus will from version 5 switch license from LGPL to Polyform Noncommercial 1.0.0 license.
With the new license EPPlus is still free to use in some cases, but will require a commercial license to be used in a commercial business.
EPPlus is a .NET library that reads and writes Excel files using the Office Open XML format (xlsx). EPPlus has no dependencies other than .NET.

EPPlus 待測

********************************************************************************

匯入 Excel (.xls) 

待測

********************************************************************************

開放文件格式 (Open Document Format, ODF)

開放文檔格式 - 維基百科,自由的百科全書
https://zh.wikipedia.org/wiki/%E5%BC%80%E6%94%BE%E6%96%87%E6%A1%A3%E6%A0%BC%E5%BC%8F

ODF 中相對 MS-Excel 的試算表檔案為 .ods (OpenDocument Spreadsheet)

Office 2010 只支援到 ODF 1.1 版,Excel 2010 開啟 LibreOffice Calc 試算表 .ods 內容會失敗,Office 2013 和 2016 才支援目前最新的 ODF 1.2版

Comparison of ODF software - The Document Foundation Wiki
ODF release dates:
ODF 1.0 May 2005
ODF 1.1 February 2007
ODF 1.2 September 2012
ODF 1.3 January 2020


How to Read and Write ODF/ODS Files (OpenDocument Spreadsheets)
28 Jul 2011
所以 odsreadwrite.zip 可能只支援到 ODF, ODS 1.1 版

Microsoft Office 2007(Service Pack 2或3)開始支援 ODF 1.1(開啟、編輯與儲存) 僅限Windows)
Microsoft Office 2013 開始支援 ODF 1.2 開啟、編輯與儲存;對 ODF 1.1僅開啟與編輯(僅限Windows)
Microsoft Office 2021 開始支援 ODF 1.3(僅限Windows)
https://support.microsoft.com/zh-tw/office/office-2021-%E7%9A%84%E6%96%B0%E5%8A%9F%E8%83%BD-43848c29-665d-4b1b-bc12-acd2bfb3910a

Comparison of ODF software - The Document Foundation Wiki
MS-Office 對 ODF 的支援並非100%
Libre Office 5.0 和 Apache OpenOffice 4.1 支援 ODF 1.0. 1.1, 1.2 

Differences between the OpenDocument Spreadsheet (.ods) format and the Excel for Windows (.xlsx) format - Microsoft Support
.ods 對 .xlsx 的支援也沒有100%,所以 .xlsx 另存為 .ods,會喪失部分資訊。

History - The Document Foundation Wiki
https://wiki.documentfoundation.org/History
  • OpenOffice.org 1.0 (May 2002) ~ 1.1.5 (Sep 2005)
  • OpenOffice.org 2.0 (Oct 2005) 支援 ODF ~ 2.4.3 (Sep 2009)
  • OpenOffice.org 3.0 (Oct 2008) ~ 3.3.0 (Jan 2011)
  • Apache OpenOffice 4.0 (Apr 2011)
LibreOffice - Wikipedia
  • LibreOffice 3.3.0 (January 25, 2011)  支援 ODF
  • LibreOffice 4.0 (February 2013)
  • LibreOffice 5.0 (August 2015)
  • LibreOffice 6.0 (31 January 2018) 支援 ODF 1.2
  • LibreOffice 7.0 (5 August 2020) 支援 ODF 1.3
Apache OpenOffice - Wikipedia
  • 3.4.0 2012-05-08,支援ODF
  • 3.4.1 2012-08-23
  • 4.0.0 2013-07-23,支援ODF 1.2
  • 4.0.1 2013-10-01
  • 4.1.0 2014-04-29
  • 4.1.1 2014-08-21
  • 4.1.2 2015-10-28
  • 4.1.3        2016-10-12
  • 4.1.4 2017-10-19
  • 4.1.5 2017-12-30
  • 4.1.6 2018-11-18
  • 4.1.7 2019-09-21
  • 4.1.9 2021-02-07,支援ODF 1.3
  • 4.1.10 2021-05-04
  • 4.1.11 2021-10-06

Libre Office 
LibreOffice_6.3.5_Win_x64_sdk.msi
https://zh-tw.libreoffice.org/download/libreoffice-still/

OpenOffice 4.1.7 SDK
https://openoffice.apache.org/downloads.html

微軟 Office 軟體對 ODF 的支援 FAQ
https://docs.microsoft.com/zh-tw/archive/blogs/officetw/office-odf-faq

[研究] C# .NET 存取 OpenOffice Calc 試算表 .ods 套件評估
http://shaurong.blogspot.com/2016/12/c-net-openoffice-calc-ods.html


Top 20 NuGet ods Packagesz

********************************************************************************

匯出、寫入ODF/.ODS

目前免費最佳做法是安裝 Java JRE  + LibreOffice + LibreOffice SDK,沒有免費好用元件,或付費買元件用。

[研究][ASP.NET]使用 Aspose.Cells 21.2.0 匯出、寫入 .ods 或 .xlsx
https://shaurong.blogspot.com/2021/02/aspnet-asposecells-2120-ods-xlsx.html
[研究][ASP.NET][C#] Aspose.Cells 評估版限制、訂價、授權、程式使用授權檔
試用版只能使用Aspose.Cells庫打開100個Excel文件。如果您的應用程序超出此數目,將引發異常。

[研究][ASP.NET]使用 OdsReaderWriter + DotNetZip 1.15.0 (Ionic.Zip) 匯出寫入 .ods

[研究][C#]匯出(寫入)、匯入(讀取) ODF/.ods 檔案 (使用 OdsReaderWriter、Ionic.Zip、DotNetZip)

[研究]Ionic.Zip 1.9.1.8 即將淘汰,替代套件 DotNetZip >= 1.9.1.8

[研究][C#][ASP.NET] GridView 匯出成 Excel / .ODF (.ods) (以Html方式輸出)
https://shaurong.blogspot.com/2020/04/caspnet-gridview-excel-odf-ods-html.html

[研究] [C#] 使用 LibreOffice 6.2.6 SDK、OpenOffice 4.1.6 SDK讀取/寫入試算表(Calc) 檔案 (.ods)
https://shaurong.blogspot.com/2019/08/c-libreoffice-626-sdk-calc-ods.html
Libre Office 或 Apache Open Office 當 .ods 的讀寫軟體就算了,它的 SDK 感覺不太穩;且
Apache OpenOffice 4.1.3 SDK (2016-10-12)  只支援 .NET 2,但不支援 .NET 4.x
LibreOffice 5.3.0 SDK (2017-01-30) 支援 .NET 4.x,但不支援 x64
.NET Framework 4.0 於 2010-04-12 釋出,兩份SDK似乎沒有很好支援.NET

NuGet 排名前面的是付費元件 (可能有免費天數限制或功能限制的版本)
https://www.nuget.org/packages?q=ODS

GemBox.Spreadsheet 是商業付費軟體,雖然有30天試用版,但功能有限制
Maximum number of rows per sheet is 150.
Maximum number of sheets per workbook is 5.

GleamTech.DocumentUltimate 是商業付費軟體,有全功能30天試用版

GroupDocs 是商業付費軟體,有全功能xx天試用版

********************************************************************************

匯入、讀取ODF/.ODS

目前免費最佳做法可能是安裝 Java JRE  + LibreOffice + LibreOffice SDK,或使用使用 .NET 4.5 的 ZipFile,沒有免費好用元件,或付費買元件用。

[研究][C#]匯出(寫入)、匯入(讀取) ODF/.ods 檔案 (使用 OdsReaderWriter、Ionic.Zip、DotNetZip)

[研究]Ionic.Zip 1.9.1.8 即將淘汰,替代套件 DotNetZip >= 1.9.1.8

[研究] [C#] 使用 LibreOffice 6.2.6 SDK、OpenOffice 4.1.6 SDK讀取/寫入試算表(Calc) 檔案 (.ods)
https://shaurong.blogspot.com/2019/08/c-libreoffice-626-sdk-calc-ods.html
這是 Windows Forms 程式

[研究] [C#] 使用 OpenOffice 4.1.3 SDK 讀取試算表(Calc) 檔案 (.ods)
http://shaurong.blogspot.com/2016/12/c-openoffice-413-sdk-calc-ods.html

[研究] [C#] 使用 LibreOffice 5.1.6、5.3.0 SDK 讀取試算表(Calc) 檔案 (.ods)
http://shaurong.blogspot.com/2016/12/c-libreoffice-516-sdk-calc-ods.html

[研究] [C#] 讀取 LibreOffice、OpenOffice 的試算表(Calc) 檔案 (.ods)(使用 .NET 4.5 的 ZipFile)
http://shaurong.blogspot.com/2016/12/c-libreoffice-516-calc-ods-net-45.html

[研究] [C#] 使用 Apose.Cells 讀取 LibreOffice 5.1.6、OpenOffice 4.1.3 試算表(Calc) 檔案 (.ods)
http://shaurong.blogspot.com/2017/01/c-aposecells-libreoffice-516openoffice.html
Apose.Cells 是商業付費元件,但有無限期的試用版,但是限制只能開啟 100 個檔案。
https://docs.aspose.com/display/cellsnet/Licensing#Licensing-EvaluationVersionLimitations

[研究] [C#] 使用 GemBox.Spreadsheet 讀取LibreOffice、OpenOffice試算表(Calc) 檔案 (.ods)
http://shaurong.blogspot.com/2016/12/c-gemboxspreadsheet-libreofficeopenoffi.html
這是商業付費軟體,雖然有30天試用版,但功能有限制
Maximum number of rows per sheet is 150.
Maximum number of sheets per workbook is 5.

[研究] OpenOffice 4.1.3 試算表(Calc) 保護鎖定儲存格不被修改
http://shaurong.blogspot.com/2016/12/openoffice-413-calc.html

[研究] 使用OpenOffice 4.1.3試算表(Calc)建立「下拉式選單」來輸入資料
http://shaurong.blogspot.com/2016/12/openoffice-413calc.html

********************************************************************************

匯出、寫入.CSV


********************************************************************************

相關文章 (其他)

[研究] 匯出、匯入 Excel 檔案 (.NET)
https://shaurong.blogspot.com/2017/11/excel-net.html

[研究] .ods、.csv 轉 .xlsx 檔案
https://shaurong.blogspot.com/2020/04/odscsv-xlsx.html

(待續)

相關文章

在 Server 端存取 Excel 檔案的利器:NPOI Library
https://msdn.microsoft.com/zh-tw/ee818993.aspx


2021年2月17日 星期三

[研究][ASP.NET]使用 ClosedXML 0.95.4 匯出、寫入 .xlsx(暫存、不暫存檔)

[研究][ASP.NET]使用 ClosedXML 0.95.4 匯出、寫入 .xlsx(暫存、不暫存檔)

2021-02-17
2021-03-16 更新
2022-03-23增加格線、自適應欄寬、水平向上對整
2022-06-13如果不存檔而直接匯出,紅字部分註解掉

環境:Visual Studio 2019 + ASP.NET + WebForm + C# + NuGet 安裝 ClosedXML 0.95.4


packages.conf
<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="ClosedXML" version="0.95.4" targetFramework="net472" />
  <package id="DocumentFormat.OpenXml" version="2.7.2" targetFramework="net472" />
  <package id="ExcelNumberFormat" version="1.0.10" targetFramework="net472" />
  <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="2.0.1" targetFramework="net472" />
  <package id="Microsoft.CSharp" version="4.7.0" targetFramework="net472" />
  <package id="System.IO.FileSystem.Primitives" version="4.0.1" targetFramework="net472" />
  <package id="System.IO.Packaging" version="4.0.0" targetFramework="net472" />
</packages>

Web.Config
<?xml version="1.0" encoding="utf-8"?>

<!--
  如需如何設定 ASP.NET 應用程式的詳細資訊,請前往
  https://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <connectionStrings>
    <add name="TestDBConnectionString" connectionString="Data Source=.;Initial Catalog=TestDB;User ID=sa;Password=P@ssw0rd"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.7.2"/>
    <httpRuntime targetFramework="4.7.2"/>
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
    </compilers>
  </system.codedom>
	<appSettings>
		<add key="TempFolder" value="D:\WWW\Temp" />
	</appSettings>
</configuration>




Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ExportXlsxByClosedTest.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                ConnectionString="<%$ ConnectionStrings:TestDBConnectionString %>" 
                SelectCommand="SELECT * FROM [Table1]"></asp:SqlDataSource>
            <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" 
                AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="SqlDataSource1">
                <Columns>
                    <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True" SortExpression="id" />
                    <asp:BoundField DataField="FieldText" HeaderText="FieldText" SortExpression="FieldText" />
                    <asp:BoundField DataField="FieldDateTime" HeaderText="FieldDateTime" SortExpression="FieldDateTime" />
                    <asp:BoundField DataField="FieldInt" HeaderText="FieldInt" SortExpression="FieldInt" />
                    <asp:CheckBoxField DataField="FieldBit" HeaderText="FieldBit" SortExpression="FieldBit" />
                </Columns>
            </asp:GridView>
            <asp:Button ID="Button_Export_Xlsx_By_ClosedXML" runat="server" 
                OnClick="Button_Export_Xlsx_By_ClosedXML_Click" Text="匯出(.xlsx)" /><br />
            <asp:Label ID="Label_MSG1" runat="server"></asp:Label>
        </div>
    </form>
</body>
</html>





Default.aspx.cs
using ClosedXML.Excel;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ExportXlsxByClosedTest
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void Button_Export_Xlsx_By_ClosedXML_Click(object sender, EventArgs e)
        {
            string mainFileName = "匯出檔案名稱";
            string fd = (string)ConfigurationManager.AppSettings["TempFolder"] + @"\";
            if (!System.IO.Directory.Exists(fd))
            {
                System.IO.Directory.CreateDirectory(fd);
            }
            string dateTimeString = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-fff");
            // 若檔案名稱有中文字或特殊符號,Response.AddHeader() 輸出檔案名稱要編碼
            string outFileName = HttpUtility.UrlEncode(
                mainFileName, System.Text.Encoding.UTF8) + "-" +
                dateTimeString + ".xlsx";

            // XLWorkbook.SaveAs() 輸出檔案名稱不要用 HttpUtility.UrlEncode 編碼
            // Response.TransmitFile() 輸出檔案名稱不要用 HttpUtility.UrlEncode 編碼
            string dirFileName = fd + mainFileName + "-" +
                dateTimeString + ".xlsx";
            try
            {
                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "";

                #region Export 

                // [EXCEL] Excel打開是亂碼?快速找回資料的最好方法!
                // http://blog.e-happy.com.tw/excel-excel%E6%89%93%E9%96%8B%E6%98%AF%E4%BA%82%E7%A2%BC%EF%BC%9F%E5%BF%AB%E9%80%9F%E6%89%BE%E5%9B%9E%E8%B3%87%E6%96%99%E7%9A%84%E6%9C%80%E5%A5%BD%E6%96%B9%E6%B3%95%EF%BC%81/

                // Excel開啟CSV時的中文編碼問題補遺
                //https://blog.darkthread.net/blog/csv-encoding-again/

                //Response.ContentType = "application/vnd.oasis.opendocument.spreadsheet";    // ODF/.ods
                //Response.AddHeader("content-disposition", "attachment;filename=" + outFileName);
                using (MemoryStream myMemoryStream = new MemoryStream())
                {
                    //StreamWriter odsFileStreamWriter = new StreamWriter(MyMemoryStream);
                    //StreamReader odsFileStreamReader = new StreamReader(new MemoryStream());
                    string dataText = "";

                    var wb = new XLWorkbook();
                    var ws = wb.Worksheets.Add("工作表1");

                   // 否則會出現類似 The range 工作表1!A1:U57 overlaps with the worksheet's autofilter. 錯誤訊息
                    ws.AutoFilter.IsEnabled = false;
                    // 定義欄位名稱列
                    string[] columnNameArray = { "id", "FieldText", "FieldDateTime", "FieldInt", "FieldBit" };
                    // Column number must be between 1 and 16384
                    for (int i = 0; i < columnNameArray.Count(); i++)
                    {
                        ws.Cell(1, i+1).Value = columnNameArray[i];
                    }

                    // 讀取資料,資料寫入「工作表1」
                    string queryString = @"
--DECLARE  @FieldText nvarchar(50)
--SET @FieldText=N'abc'

SELECT * FROM [TestDB].[dbo].[Table1]
";

                    using (SqlConnection connection = new SqlConnection(
                        WebConfigurationManager.ConnectionStrings["TestDBConnectionString"].ConnectionString))
                    {
                        SqlCommand command = new SqlCommand(queryString, connection);
                        //command.Parameters.Clear();
                        //command.Parameters.AddWithValue("@FieldText", queryFieldText);
                        connection.Open();
                        SqlDataReader reader = command.ExecuteReader();
                        int rowIndex = 1;   // 1 是標題列
                        while (reader.Read())
                        {
                            rowIndex++;
                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                //reader[i]的 i 要從 0 開始
                                dataText = reader[i].ToString();

                                // 規則運算式語言 - 快速參考 | Microsoft Docs
                                // https://docs.microsoft.com/zh-tw/dotnet/standard/base-types/regular-expression-language-quick-reference

                                // 換掉特殊字元 (自己評估)
                                dataText = dataText.Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace(",", ",").Replace("'", "′").Replace(@"""", "”");
                                dataText = dataText.Replace("\a", "").Replace("\b", "").Replace("\t", "").Replace("\v", "").Replace("\f", "").Replace("\\", "");

                                // Column number must be between 1 and 16384
                                ws.Cell(rowIndex, i+1).Value = dataText;
                            }
                        }

                        //設定區域範圍的  儲存格框線
                        //ws.Ranges("A1:F5").Style.Border.TopBorder = XLBorderStyleValues.Thin;
                        string endCell = "S" + rowIndex.ToString();
                        ws.Ranges("A1:" + endCell).Style.Border.TopBorder = XLBorderStyleValues.Thin;
                        ws.Ranges("A1:" + endCell).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
                        ws.Ranges("A1:" + endCell).Style.Border.RightBorder = XLBorderStyleValues.Thin;
                        ws.Ranges("A1:" + endCell).Style.Border.BottomBorder = XLBorderStyleValues.Thin;

                        ws.Columns().AdjustToContents();// 自適應欄寬,這要在資料寫完後,檔案儲存關閉前再做

                        ws.Ranges("A1:" + endCell).Style.Alignment.Vertical = XLAlignmentVerticalValues.Top; // 水平向上對齊

                        Response.Clear();
                        Response.Buffer = true;
                        Response.ContentEncoding = Encoding.GetEncoding(950);   //950就是所謂的BIG5
                                                                                //Response.AddHeader("Content-Disposition", "attachment;filename=\"" +
                                                                                //    HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + "-" +
                                                                                //    DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx");
                        Response.AddHeader("Content-Disposition", "attachment;filename=\"" + outFileName);
                        //'Excel 2003 : "application/vnd.ms-excel"
                        //'Excel 2007 : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

                        //Extension       MIME Type
                        //.xlsx               application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
                        //.xltx                application/vnd.openxmlformats-officedocument.spreadsheetml.template
                        //.potx               application/vnd.openxmlformats-officedocument.presentationml.template
                        //.ppsx              application/vnd.openxmlformats-officedocument.presentationml.slideshow
                        //.pptx               application/vnd.openxmlformats-officedocument.presentationml.presentation
                        //.sldx               application/vnd.openxmlformats-officedocument.presentationml.slide
                        //.docx              application/vnd.openxmlformats-officedocument.wordprocessingml.document
                        //.dotx               application/vnd.openxmlformats-officedocument.wordprocessingml.template
                        //.xlam              application/vnd.ms-excel.addin.macroEnabled.12
                        //.xlsb               application/vnd.ms-excel.sheet.binary.macroEnabled.12

                        //Response.ContentType = "application/ms-excel";
                        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

                        //Response.TransmitFile(@"C:\Program Files (x86)\IIS Express\Export.xlsx");
                        //dirFileName = dirFileName.Replace('\\', '/');   //轉換 Windows, Linux 不同路徑斜線
                        //dirFileName = dirFileName.Replace("/", "\\");  // 轉換斜線 / 成 \  ,因 \ 是特殊符號,要以 \\ 表示

                        // 方法1: 直接輸出
                        wb.SaveAs(myMemoryStream);
                        Response.BinaryWrite(myMemoryStream.ToArray());
                        // myMemoryStream.WriteTo(Response.OutputStream); //works too
                        Response.Flush();
                        Response.Close();
                        
                        // 方法2: 若需要寫入檔案再輸出
                        wb.SaveAs(dirFileName);                 // 存檔,Debug 或其他用途
                        ////Response.WriteFile(savePath);
                        //Response.TransmitFile(dirFileName);   // 把存檔輸出
                        
                        // 輸出結束
                        Response.End();

                        Label_MSG1.ForeColor = System.Drawing.Color.Green;
                        Label_MSG1.Text = "匯出成功。";
                        // 上面 Response 輸出檔案,所以下面 JavaScript alert 是不會跳出的
                        //Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('匯出成功。');</script>");
                    }
                }
                #endregion Export ODS
            }
            catch (Exception ex)
            {
                Label_MSG1.ForeColor = System.Drawing.Color.Red;
                string exMsg = "不明錯誤。";
                if (ex != null)
                {
                    exMsg = ex.ToString();
                }
                Label_MSG1.Text = exMsg;
                Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('匯出失敗。');</script>");
                // Exception Message 內容可能導致 JavaScript alert 無法顯示,所以下面這行可能無法跳出對話盒視窗。
                Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('" + exMsg + "');</script>");
            }
        }
        // ----------
    }
}

不過根據以往經驗,元件直接產生的 .xlsx,和用 Excel 建立的 .xlsx,實際的檔案骨架 schema 好像沒有 100% 相同,前者用某些元件或版本匯入可能正常或會出錯,但前者用 Microsoft Excel 軟體直接開啟正常。

或可考慮先用 Excel 2016 或 Excel 2019 做好一個沒填寫內容的 活頁簿 (Workbook) 和 工作表1 (Worksheet),複製後 (避免多人同開開起讀寫),再拿來寫入、關閉、匯出。

(完)

相關

[研究][ASP.NET]ClosedXML元件常用屬性或方法http://shaurong.blogspot.com/2022/04/aspnetclosedxml.html

[研究][ASP.NET]使用 ClosedXML 0.95.4 讀取匯入 .xlsx 到資料庫(暫存、不暫存檔)
http://shaurong.blogspot.com/2021/02/aspnet-closedxml-0954-xlsx.html

[研究][ASP.NET]使用 ClosedXML 0.95.4 匯出、寫入 .xlsx(暫存、不暫存檔)
http://shaurong.blogspot.com/2021/02/aspnet-closedxml-0954-xlsx_17.html




2021年2月9日 星期二

[研究][ASP.NET]使用 Aspose.Cells 21.2.0 匯出、寫入 .ods 或 .xlsx

[研究][ASP.NET]使用 Aspose.Cells 21.2.0 匯出、寫入 .ods 或 .xlsx

2021-02-09

環境:Visual Studio 2019 + ASP.NET + WebForm + C# + NuGet 安裝 Aspose.Cells 21.2.0


packages.conf
<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Aspose.Cells" version="21.2.0" targetFramework="net472" />
  <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="2.0.1" targetFramework="net472" />
</packages>

Web.Config
<?xml version="1.0" encoding="utf-8"?>

<!--
  如需如何設定 ASP.NET 應用程式的詳細資訊,請前往
  https://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <connectionStrings>
    <add name="TestDBConnectionString" connectionString="Data Source=.;Initial Catalog=TestDB;User ID=sa;Password=P@ssw0rd"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.7.2"/>
    <httpRuntime targetFramework="4.7.2"/>
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
    </compilers>
  </system.codedom>
	<appSettings>
		<add key="AsposelicFolder" value="D:\Production\Asposelic" />
		<add key="TempFolder" value="D:\WWW\Temp" />
	</appSettings>
</configuration>



Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ExportOdsXlsxByAsposeCellsTest.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                ConnectionString="<%$ ConnectionStrings:TestDBConnectionString %>" 
                SelectCommand="SELECT * FROM [Table1]"></asp:SqlDataSource>
            <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" 
                AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="SqlDataSource1">
                <Columns>
                    <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True" SortExpression="id" />
                    <asp:BoundField DataField="FieldText" HeaderText="FieldText" SortExpression="FieldText" />
                    <asp:BoundField DataField="FieldDateTime" HeaderText="FieldDateTime" SortExpression="FieldDateTime" />
                    <asp:BoundField DataField="FieldInt" HeaderText="FieldInt" SortExpression="FieldInt" />
                    <asp:CheckBoxField DataField="FieldBit" HeaderText="FieldBit" SortExpression="FieldBit" />
                </Columns>
            </asp:GridView>
            <asp:Button ID="Button_Export_Ods_By_AsposeCells" runat="server" 
                OnClick="Button_Export_Ods_By_AsposeCells_Click" Text="匯出(.ods)" /><br />
            <asp:Label ID="Label_MSG1" runat="server"></asp:Label>
        </div>
    </form>
</body>
</html>




Default.aspx.cs
using Aspose.Cells;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ExportOdsXlsxByAsposeCellsTest
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button_Export_Ods_By_AsposeCells_Click(object sender, EventArgs e)
        {
            // 設定和使用 Aspose.Cells 授權 (Begin)
            string asposelicFolder = ConfigurationManager.AppSettings["AsposelicFolder"];
            Aspose.Cells.License license = new Aspose.Cells.License();
            license.SetLicense(asposelicFolder + "/Aspose.Cells.lic");
            // 設定和使用 Aspose.Cells 授權 (End)

            string mainFileName = "匯出檔案名稱";
            string fd = (string)ConfigurationManager.AppSettings["TempFolder"] + @"\";
            if (!System.IO.Directory.Exists(fd))
            {
                System.IO.Directory.CreateDirectory(fd);
            }
            string dateTimeString = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-fff");
            // 若檔案名稱有中文字或特殊符號,Response.AddHeader() 輸出檔案名稱要編碼
            string outFileName = HttpUtility.UrlEncode(
                mainFileName, System.Text.Encoding.UTF8) + "-" +
                dateTimeString + ".ods";

            // XLWorkbook.SaveAs() 輸出檔案名稱不要用 HttpUtility.UrlEncode 編碼
            // Response.TransmitFile() 輸出檔案名稱不要用 HttpUtility.UrlEncode 編碼
            string dirFileName = fd + mainFileName + "-" +
                dateTimeString + ".ods";
            try
            {
                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "";

                #region Export ODS

                // [EXCEL] Excel打開是亂碼?快速找回資料的最好方法!
                // http://blog.e-happy.com.tw/excel-excel%E6%89%93%E9%96%8B%E6%98%AF%E4%BA%82%E7%A2%BC%EF%BC%9F%E5%BF%AB%E9%80%9F%E6%89%BE%E5%9B%9E%E8%B3%87%E6%96%99%E7%9A%84%E6%9C%80%E5%A5%BD%E6%96%B9%E6%B3%95%EF%BC%81/

                // Excel開啟CSV時的中文編碼問題補遺
                //https://blog.darkthread.net/blog/csv-encoding-again/

                Response.ContentType = "application/vnd.oasis.opendocument.spreadsheet";    // ODF/.ods
                Response.AddHeader("content-disposition", "attachment;filename=" + outFileName);
                using (MemoryStream MyMemoryStream = new MemoryStream())
                {
                    StreamWriter odsFileStreamWriter = new StreamWriter(MyMemoryStream);
                    StreamReader odsFileStreamReader = new StreamReader(new MemoryStream());
                    string dataText = "";

                    Aspose.Cells.Workbook book = new Workbook();
                    Aspose.Cells.Worksheet sheet = book.Worksheets[0];
                    Cells cells = sheet.Cells;

                    DataSet ds = new DataSet("DS1");
                    DataTable dt = ds.Tables.Add("工作表1");

                    // 定義欄位名稱列
                    string[] columnNameArray = { "id", "FieldText", "FieldDateTime", "FieldInt", "FieldBit" };
                    for (int i=0; i< columnNameArray.Count(); i++)
                    {
                        cells[0, i].PutValue(columnNameArray[i]);
                    }

                    // 讀取資料,資料寫入「工作表1」
                    string queryString = @"
--DECLARE  @FieldText nvarchar(50)
--SET @FieldText=N'abc'

SELECT * FROM [TestDB].[dbo].[Table1]
";

                    using (SqlConnection connection = new SqlConnection(
                        WebConfigurationManager.ConnectionStrings["TestDBConnectionString"].ConnectionString))
                    {
                        SqlCommand command = new SqlCommand(queryString, connection);
                        //command.Parameters.Clear();
                        //command.Parameters.AddWithValue("@FieldText", queryFieldText);
                        connection.Open();
                        SqlDataReader reader = command.ExecuteReader();
                        int rowIndex = 0;   // 0 是標題列
                        while (reader.Read())
                        {
                            rowIndex++;
                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                dataText = reader[i].ToString();

                                // 規則運算式語言 - 快速參考 | Microsoft Docs
                                // https://docs.microsoft.com/zh-tw/dotnet/standard/base-types/regular-expression-language-quick-reference

                                // 換掉特殊字元 (自己評估)
                                dataText = dataText.Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace(",", ",").Replace("'", "′").Replace(@"""", "”");
                                dataText = dataText.Replace("\a", "").Replace("\b", "").Replace("\t", "").Replace("\v", "").Replace("\f", "").Replace("\\", "");

                                cells[rowIndex, i].PutValue(dataText);
                            }
                        }

                        book.Save(dirFileName);
                        //System.Threading.Thread.Sleep(1000);

                        //Response.WriteFile(savePath);
                        Response.TransmitFile(dirFileName);
                        Response.End();

                        Label_MSG1.ForeColor = System.Drawing.Color.Green;
                        Label_MSG1.Text = "匯出成功。";
                        // 上面 Response 輸出檔案,所以下面 JavaScript alert 是不會跳出的
                        //Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('匯出成功。');</script>");
                    }
                }
                #endregion Export ODS
            }
            catch (Exception ex)
            {
                Label_MSG1.ForeColor = System.Drawing.Color.Red;
                string exMsg = "不明錯誤。";
                if (ex != null)
                {
                    exMsg = ex.ToString();
                }
                Label_MSG1.Text = exMsg;
                Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('匯出失敗。');</script>");
                // Exception Message 內容可能導致 JavaScript alert 無法顯示,所以下面這行可能無法跳出對話盒視窗。
                Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('" + exMsg + "');</script>");
            }
        }
        // ----------
    }
}

把 .ods 改成 .xlsx,就可以匯出 .xlsx 檔案。

(完)

[研究][ASP.NET]使用 OdsReaderWriter + DotNetZip 1.15.0 (Ionic.Zip) 匯出寫入 .ods

[研究][ASP.NET]使用 OdsReaderWriter +  DotNetZip 1.15.0 (Ionic.Zip) 匯出寫入 .ods

2021-02-09

ODF release dates:

  • ODF 1.0 May 2005
  • ODF 1.1 February 2007
  • ODF 1.2 September 2012
  • ODF 1.3 January 2020

https://wiki.documentfoundation.org/Comparison_of_ODF_software

How to Read and Write ODF/ODS Files (OpenDocument Spreadsheets)
28 Jul 2011
https://www.codeproject.com/Articles/38425/How-to-Read-and-Write-ODF-ODS-Files-OpenDocument-2
所以 odsreadwrite.zip 可能只支援到 ODF, ODS 1.1 版

環境:Visual Studio 2019 + ASP.NET + WebForm + C# + NuGet 安裝 NPOI 2.5.2

暫存目錄要設定程式或 IIS_IUSRS 或 IUSR 可以寫入。
( 如果是 deploy 發佈到 ASP.NET + IIS 網站, IIS_IUSRS 可以寫入即可)
( 如果是 deploy 發佈到  IIS +某種 CGI 網站, IUSR 需可以寫入)



Web.Config
<?xml version="1.0" encoding="utf-8"?>

<!--
  如需如何設定 ASP.NET 應用程式的詳細資訊,請前往
  https://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <connectionStrings>
    <add name="TestDBConnectionString" connectionString="Data Source=.;Initial Catalog=TestDB;User ID=sa;Password=P@ssw0rd"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.7.2"/>
    <httpRuntime targetFramework="4.7.2"/>
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
    </compilers>
  </system.codedom>
	<appSettings>
		<add key="TempFolder" value="D:\WWW\Temp" />
	</appSettings>
</configuration>


packages.config
<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="DotNetZip" version="1.15.0" targetFramework="net472" />
  <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="2.0.1" targetFramework="net472" />
</packages>

Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
    Inherits="ExportOdsByOdsReaderWriterDotNetZipTest.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                ConnectionString="<%$ ConnectionStrings:TestDBConnectionString %>" 
                SelectCommand="SELECT * FROM [Table1]"></asp:SqlDataSource>
            <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" 
                AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="SqlDataSource1">
                <Columns>
                    <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True" SortExpression="id" />
                    <asp:BoundField DataField="FieldText" HeaderText="FieldText" SortExpression="FieldText" />
                    <asp:BoundField DataField="FieldDateTime" HeaderText="FieldDateTime" SortExpression="FieldDateTime" />
                    <asp:BoundField DataField="FieldInt" HeaderText="FieldInt" SortExpression="FieldInt" />
                    <asp:CheckBoxField DataField="FieldBit" HeaderText="FieldBit" SortExpression="FieldBit" />
                </Columns>
            </asp:GridView>
            <asp:Button ID="Button_Export_Ods_By_OdsReaderWriter_DotNetZip" runat="server" 
                OnClick="Button_Export_Ods_By_OdsReaderWriter_DotNetZip_Click" Text="匯出(.ods)" /><br />
            <asp:Label ID="Label_MSG1" runat="server"></asp:Label>
        </div>
    </form>
</body>
</html>





Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using OdsReadWrite;   //  要 using  namespace ,才能存取到 OdsReadWriter 這個 class

namespace ExportOdsByOdsReaderWriterDotNetZipTest
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button_Export_Ods_By_OdsReaderWriter_DotNetZip_Click(object sender, EventArgs e)
        {
            /*
            OdsReaderWriter.cs 和 template.ods 取自下面網站
            How to Read and Write ODF/ODS Files (OpenDocument Spreadsheets)
            https://www.codeproject.com/Articles/38425/How-to-Read-and-Write-ODF-ODS-Files-OpenDocument-2
           
            template.ods 請自己用 Excel、OpenOffice 或 LibreOffice 的 Calc 建立一個空的即可。
           
            NuGet 要安裝 Ionic.Zip 套件。(Ionic.Zip 已經淘汰,請改用DotNetZip)
            */

            string mainFileName = "匯出檔案名稱";
            string fd = (string)ConfigurationManager.AppSettings["TempFolder"] + @"\";
            if (!System.IO.Directory.Exists(fd))
            {
                System.IO.Directory.CreateDirectory(fd);
            }
            string dateTimeString = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-fff");
            // 若檔案名稱有中文字或特殊符號,Response.AddHeader() 輸出檔案名稱要編碼
            string outFileName = HttpUtility.UrlEncode(
                mainFileName, System.Text.Encoding.UTF8) + "-" +
                dateTimeString + ".ods";

            // XLWorkbook.SaveAs() 輸出檔案名稱不要用 HttpUtility.UrlEncode 編碼
            // Response.TransmitFile() 輸出檔案名稱不要用 HttpUtility.UrlEncode 編碼
            string dirFileName = fd + mainFileName + "-" +
                dateTimeString + ".ods";
            try
            {
                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "";

                #region Export ODS

                // [EXCEL] Excel打開是亂碼?快速找回資料的最好方法!
                // http://blog.e-happy.com.tw/excel-excel%E6%89%93%E9%96%8B%E6%98%AF%E4%BA%82%E7%A2%BC%EF%BC%9F%E5%BF%AB%E9%80%9F%E6%89%BE%E5%9B%9E%E8%B3%87%E6%96%99%E7%9A%84%E6%9C%80%E5%A5%BD%E6%96%B9%E6%B3%95%EF%BC%81/

                // Excel開啟CSV時的中文編碼問題補遺
                //https://blog.darkthread.net/blog/csv-encoding-again/

                Response.ContentType = "application/vnd.oasis.opendocument.spreadsheet";    // ODF/.ods
                Response.AddHeader("content-disposition", "attachment;filename=" + outFileName);
                using (MemoryStream MyMemoryStream = new MemoryStream())
                {
                    StreamWriter odsFileStreamWriter = new StreamWriter(MyMemoryStream);
                    StreamReader odsFileStreamReader = new StreamReader(new MemoryStream());
                    string dataText = "";

                    DataSet ds = new DataSet("DS1");
                    DataTable dt = ds.Tables.Add("工作表1");

                    // 定義欄位名稱列
                    string[] columnNameArray = { "id", "FieldText", "FieldDateTime", "FieldInt", "FieldBit" };
                    foreach (string columnName in columnNameArray)
                    {
                        DataColumn dataColumnName = new DataColumn();
                        dataColumnName.DataType = System.Type.GetType("System.String");
                        dataColumnName.ColumnName = columnName;
                        //fNameColumn.DefaultValue = "Fname";
                        dt.Columns.Add(dataColumnName);
                    }
                    //dt.Columns.Add(new DataColumn("FieldText", typeof(string)));

                    // 把欄位名稱列寫入「工作表1」
                    DataRow dataColumnNameRow = dt.NewRow();
                    int ii = 0;
                    foreach (string columnName in columnNameArray)
                    {
                        dataColumnNameRow[ii] = columnName;
                        ii++;
                    }
                    dt.Rows.Add(dataColumnNameRow);

                    // 讀取資料,資料寫入「工作表1」
                    string queryString = @"
--DECLARE  @FieldText nvarchar(50)
--SET @FieldText=N'abc'

SELECT * FROM [TestDB].[dbo].[Table1]
";

                    using (SqlConnection connection = new SqlConnection(
                        WebConfigurationManager.ConnectionStrings["TestDBConnectionString"].ConnectionString))
                    {
                        SqlCommand command = new SqlCommand(queryString, connection);
                        //command.Parameters.Clear();
                        //command.Parameters.AddWithValue("@FieldText", queryFieldText);
                        connection.Open();
                        try
                        {
                            SqlDataReader reader = command.ExecuteReader();
                            while (reader.Read())
                            {
                                //Console.WriteLine(String.Format("{0}", reader[0]));
                                DataRow datarow = dt.NewRow();
                                for (int i = 0; i < reader.FieldCount; i++)
                                {
                                    dataText = reader[i].ToString();
                                    // 逸出字元 | Microsoft Docs
                                    // https://docs.microsoft.com/zh-tw/dotnet/standard/base-types/regular-expression-language-quick-reference
                                    // 換掉特殊字元
                                    dataText = dataText.Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace(",", ",").Replace("'", "′").Replace(@"""", "”");                                          dataText = dataText.Replace("\a", "").Replace("\b", "").Replace("\t", "").Replace("\v", "").Replace("\f", "").Replace("\\", "");
                                    datarow[i] = dataText;
                                }
                                dt.Rows.Add(datarow);
                            }

                            //GridView1.DataSourceID = "";
                            //GridView1.DataSource = ds;    // Fail, ds 是 null 嗎?
                            //GridView1.DataBind();

                            OdsReaderWriter odsFile = new OdsReaderWriter();
                            //odsFile.WriteOdsFile(ds, @"C:\TEMP\1.ods");
                            odsFile.WriteOdsFile(ds, dirFileName);  // Fail, ds 是 null 嗎?

                            Response.TransmitFile(dirFileName);
                            Response.End();

                            Label_MSG1.ForeColor = System.Drawing.Color.Green;
                            Label_MSG1.Text = "匯出成功。";
                            // 上面 Response 輸出檔案,所以下面 JavaScript alert 是不會跳出的
                            //Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('匯出成功。');</script>");
                        }
                        catch (Exception ex)
                        {
                            string errMsg = "#3: 不明例外。";
                            Label_MSG1.ForeColor = System.Drawing.Color.Red;
                            if (ex != null)
                            {
                                errMsg = "#3: " + ex.Message.ToString();
                            }
                            Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('" + errMsg + "');</script>");
                        }
                    }
                }
                #endregion Export ODS
            }
            catch (Exception ex)
            {
                Label_MSG1.ForeColor = System.Drawing.Color.Red;
                string exMsg = "不明錯誤。";
                if (ex != null)
                {
                    exMsg = ex.ToString();
                }
                Label_MSG1.Text = exMsg;
                Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('匯出失敗。');</script>");
                // Exception Message 內容可能導致 JavaScript alert 無法顯示,所以下面這行可能無法跳出對話盒視窗。
                Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('" + exMsg + "');</script>");
            }
        }
        // ----------
    }
}


OdsReaderWriter.cs

要做點修改 ZipFile templateFile 那行

https://www.codeproject.com/Articles/38425/How-to-Read-and-Write-ODF-ODS-Files-OpenDocument-2
using System;
using System.Data;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Web;
using System.Xml;

// Ionic.Zip 已經淘汰,請改用 DotNetZip
// 不管 NuGet 安裝 DotNetZip 或 Ionic.Zip,Using 都是 Ionic.Zip
using Ionic.Zip;

namespace OdsReadWrite
{
    internal sealed class OdsReaderWriter
    {
        // Namespaces. We need this to initialize XmlNamespaceManager so that we can search XmlDocument.
        private static string[,] namespaces = new string[,] 
        {
            {"table", "urn:oasis:names:tc:opendocument:xmlns:table:1.0"},
            {"office", "urn:oasis:names:tc:opendocument:xmlns:office:1.0"},
            {"style", "urn:oasis:names:tc:opendocument:xmlns:style:1.0"},
            {"text", "urn:oasis:names:tc:opendocument:xmlns:text:1.0"},            
            {"draw", "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"},
            {"fo", "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"},
            {"dc", "http://purl.org/dc/elements/1.1/"},
            {"meta", "urn:oasis:names:tc:opendocument:xmlns:meta:1.0"},
            {"number", "urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0"},
            {"presentation", "urn:oasis:names:tc:opendocument:xmlns:presentation:1.0"},
            {"svg", "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"},
            {"chart", "urn:oasis:names:tc:opendocument:xmlns:chart:1.0"},
            {"dr3d", "urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0"},
            {"math", "http://www.w3.org/1998/Math/MathML"},
            {"form", "urn:oasis:names:tc:opendocument:xmlns:form:1.0"},
            {"script", "urn:oasis:names:tc:opendocument:xmlns:script:1.0"},
            {"ooo", "http://openoffice.org/2004/office"},
            {"ooow", "http://openoffice.org/2004/writer"},
            {"oooc", "http://openoffice.org/2004/calc"},
            {"dom", "http://www.w3.org/2001/xml-events"},
            {"xforms", "http://www.w3.org/2002/xforms"},
            {"xsd", "http://www.w3.org/2001/XMLSchema"},
            {"xsi", "http://www.w3.org/2001/XMLSchema-instance"},
            {"rpt", "http://openoffice.org/2005/report"},
            {"of", "urn:oasis:names:tc:opendocument:xmlns:of:1.2"},
            {"rdfa", "http://docs.oasis-open.org/opendocument/meta/rdfa#"},
            {"config", "urn:oasis:names:tc:opendocument:xmlns:config:1.0"}
        };

        // Read zip stream (.ods file is zip file).
        private ZipFile GetZipFile(Stream stream)
        {
            return ZipFile.Read(stream);
        }

        // Read zip file (.ods file is zip file).
        private ZipFile GetZipFile(string inputFilePath)
        {
            return ZipFile.Read(inputFilePath);
        }

        private XmlDocument GetContentXmlFile(ZipFile zipFile)
        {
            // Get file(in zip archive) that contains data ("content.xml").
            ZipEntry contentZipEntry = zipFile["content.xml"];

            // Extract that file to MemoryStream.
            Stream contentStream = new MemoryStream();
            contentZipEntry.Extract(contentStream);
            contentStream.Seek(0, SeekOrigin.Begin);

            // Create XmlDocument from MemoryStream (MemoryStream contains content.xml).
            XmlDocument contentXml = new XmlDocument();
            contentXml.Load(contentStream);

            return contentXml;
        }

        private XmlNamespaceManager InitializeXmlNamespaceManager(XmlDocument xmlDocument)
        {
            XmlNamespaceManager nmsManager = new XmlNamespaceManager(xmlDocument.NameTable);

            for (int i = 0; i < namespaces.GetLength(0); i++)
                nmsManager.AddNamespace(namespaces[i, 0], namespaces[i, 1]);

            return nmsManager;
        }

        /// <summary>
        /// Read .ods file and store it in DataSet.
        /// </summary>
        /// <param name="inputFilePath">Path to the .ods file.</param>
        /// <returns>DataSet that represents .ods file.</returns>
        public DataSet ReadOdsFile(string inputFilePath)
        {
            ZipFile odsZipFile = this.GetZipFile(inputFilePath);

            // Get content.xml file
            XmlDocument contentXml = this.GetContentXmlFile(odsZipFile);

            // Initialize XmlNamespaceManager
            XmlNamespaceManager nmsManager = this.InitializeXmlNamespaceManager(contentXml);

            DataSet odsFile = new DataSet(Path.GetFileName(inputFilePath));

            foreach (XmlNode tableNode in this.GetTableNodes(contentXml, nmsManager))
                odsFile.Tables.Add(this.GetSheet(tableNode, nmsManager));

            return odsFile;
        }

        // In ODF sheet is stored in table:table node
        private XmlNodeList GetTableNodes(XmlDocument contentXmlDocument, XmlNamespaceManager nmsManager)
        {
            return contentXmlDocument.SelectNodes("/office:document-content/office:body/office:spreadsheet/table:table", nmsManager);
        }

        private DataTable GetSheet(XmlNode tableNode, XmlNamespaceManager nmsManager)
        {
            DataTable sheet = new DataTable(tableNode.Attributes["table:name"].Value);

            XmlNodeList rowNodes = tableNode.SelectNodes("table:table-row", nmsManager);

            int rowIndex = 0;
            foreach (XmlNode rowNode in rowNodes)
                this.GetRow(rowNode, sheet, nmsManager, ref rowIndex);

            return sheet;
        }

        private void GetRow(XmlNode rowNode, DataTable sheet, XmlNamespaceManager nmsManager, ref int rowIndex)
        {
            XmlAttribute rowsRepeated = rowNode.Attributes["table:number-rows-repeated"];
            if (rowsRepeated == null || Convert.ToInt32(rowsRepeated.Value, CultureInfo.InvariantCulture) == 1)
            {
                while (sheet.Rows.Count < rowIndex)
                    sheet.Rows.Add(sheet.NewRow());

                DataRow row = sheet.NewRow();

                XmlNodeList cellNodes = rowNode.SelectNodes("table:table-cell", nmsManager);

                int cellIndex = 0;
                foreach (XmlNode cellNode in cellNodes)
                    this.GetCell(cellNode, row, nmsManager, ref cellIndex);

                sheet.Rows.Add(row);

                rowIndex++;
            }
            else
            {
                rowIndex += Convert.ToInt32(rowsRepeated.Value, CultureInfo.InvariantCulture);
            }

            // sheet must have at least one cell
            if (sheet.Rows.Count == 0)
            {
                sheet.Rows.Add(sheet.NewRow());
                sheet.Columns.Add();
            }
        }

        private void GetCell(XmlNode cellNode, DataRow row, XmlNamespaceManager nmsManager, ref int cellIndex)
        {
            XmlAttribute cellRepeated = cellNode.Attributes["table:number-columns-repeated"];

            if (cellRepeated == null)
            {
                DataTable sheet = row.Table;

                while (sheet.Columns.Count <= cellIndex)
                    sheet.Columns.Add();

                row[cellIndex] = this.ReadCellValue(cellNode);

                cellIndex++;
            }
            else
            {
                cellIndex += Convert.ToInt32(cellRepeated.Value, CultureInfo.InvariantCulture);
            }
        }

        private string ReadCellValue(XmlNode cell)
        {
            XmlAttribute cellVal = cell.Attributes["office:value"];

            if (cellVal == null)
                return String.IsNullOrEmpty(cell.InnerText) ? null : cell.InnerText;
            else
                return cellVal.Value;
        }

        /// <summary>
        /// Writes DataSet as .ods file.
        /// </summary>
        /// <param name="odsFile">DataSet that represent .ods file.</param>
        /// <param name="outputFilePath">The name of the file to save to.</param>
        public void WriteOdsFile(DataSet odsFile, string outputFilePath)
        {
            //ZipFile templateFile = this.GetZipFile(Assembly.GetExecutingAssembly().GetManifestResourceStream("OdsReadWrite.template.ods"));
            //ZipFile templateFile = this.GetZipFile(File.OpenRead(@"C:\CODE\ODSExport\ODSExport\bin\template.ods"));
            //ZipFile templateFile = this.GetZipFile(File.OpenRead(Server.MapPath("/") + "template.ods");
            ZipFile templateFile = this.GetZipFile(File.OpenRead(HttpContext.Current.Server.MapPath("/template.ods")));

            XmlDocument contentXml = this.GetContentXmlFile(templateFile);

            XmlNamespaceManager nmsManager = this.InitializeXmlNamespaceManager(contentXml);

            XmlNode sheetsRootNode = this.GetSheetsRootNodeAndRemoveChildrens(contentXml, nmsManager);

            foreach (DataTable sheet in odsFile.Tables)
                this.SaveSheet(sheet, sheetsRootNode);

            this.SaveContentXml(templateFile, contentXml);

            templateFile.Save(outputFilePath);
        }

        private XmlNode GetSheetsRootNodeAndRemoveChildrens(XmlDocument contentXml, XmlNamespaceManager nmsManager)
        {
            XmlNodeList tableNodes = this.GetTableNodes(contentXml, nmsManager);

            XmlNode sheetsRootNode = tableNodes.Item(0).ParentNode;
            // remove sheets from template file
            foreach (XmlNode tableNode in tableNodes)
                sheetsRootNode.RemoveChild(tableNode);

            return sheetsRootNode;
        }

        private void SaveSheet(DataTable sheet, XmlNode sheetsRootNode)
        {
            XmlDocument ownerDocument = sheetsRootNode.OwnerDocument;

            XmlNode sheetNode = ownerDocument.CreateElement("table:table", this.GetNamespaceUri("table"));

            XmlAttribute sheetName = ownerDocument.CreateAttribute("table:name", this.GetNamespaceUri("table"));
            sheetName.Value = sheet.TableName;
            sheetNode.Attributes.Append(sheetName);

            this.SaveColumnDefinition(sheet, sheetNode, ownerDocument);

            this.SaveRows(sheet, sheetNode, ownerDocument);

            sheetsRootNode.AppendChild(sheetNode);
        }

        private void SaveColumnDefinition(DataTable sheet, XmlNode sheetNode, XmlDocument ownerDocument)
        {
            XmlNode columnDefinition = ownerDocument.CreateElement("table:table-column", this.GetNamespaceUri("table"));

            XmlAttribute columnsCount = ownerDocument.CreateAttribute("table:number-columns-repeated", this.GetNamespaceUri("table"));
            columnsCount.Value = sheet.Columns.Count.ToString(CultureInfo.InvariantCulture);
            columnDefinition.Attributes.Append(columnsCount);

            sheetNode.AppendChild(columnDefinition);
        }

        private void SaveRows(DataTable sheet, XmlNode sheetNode, XmlDocument ownerDocument)
        {
            DataRowCollection rows = sheet.Rows;
            for (int i = 0; i < rows.Count; i++)
            {
                XmlNode rowNode = ownerDocument.CreateElement("table:table-row", this.GetNamespaceUri("table"));

                this.SaveCell(rows[i], rowNode, ownerDocument);

                sheetNode.AppendChild(rowNode);
            }
        }

        private void SaveCell(DataRow row, XmlNode rowNode, XmlDocument ownerDocument)
        {
            object[] cells = row.ItemArray;

            for (int i = 0; i < cells.Length; i++)
            {
                XmlElement cellNode = ownerDocument.CreateElement("table:table-cell", this.GetNamespaceUri("table"));

                if (row[i] != DBNull.Value)
                {
                    // We save values as text (string)
                    XmlAttribute valueType = ownerDocument.CreateAttribute("office:value-type", this.GetNamespaceUri("office"));
                    valueType.Value = "string";
                    cellNode.Attributes.Append(valueType);

                    XmlElement cellValue = ownerDocument.CreateElement("text:p", this.GetNamespaceUri("text"));
                    cellValue.InnerText = row[i].ToString();
                    cellNode.AppendChild(cellValue);
                }

                rowNode.AppendChild(cellNode);
            }
        }

        private void SaveContentXml(ZipFile templateFile, XmlDocument contentXml)
        {
            templateFile.RemoveEntry("content.xml");

            MemoryStream memStream = new MemoryStream();
            contentXml.Save(memStream);
            memStream.Seek(0, SeekOrigin.Begin);

            templateFile.AddEntry("content.xml", memStream);
        }

        private string GetNamespaceUri(string prefix)
        {
            for (int i = 0; i < namespaces.GetLength(0); i++)
            {
                if (namespaces[i, 0] == prefix)
                    return namespaces[i, 1];
            }

            throw new InvalidOperationException("Can't find that namespace URI");
        }
    }
}





(完)