顯示具有 ClosedXML 標籤的文章。 顯示所有文章
顯示具有 ClosedXML 標籤的文章。 顯示所有文章

2026年8月14日 星期五

[研究]ASP.NET WebForm + ClosedXML 0.105.1相依與升級SixLabors.Fonts

[研究]ASP.NET WebForm + ClosedXML 0.105.1相依與升級SixLabors.Fonts

2026-08-14

ASP.NET WebForm + .NET Framework 4.8.1 網站,如果 Windows 安裝 .NET 8,.NET Framework 的 ClosedXML 0.105.1 可以使用 SixLabors.Fonts 2.0 或 SixLabors.Fonts 3.0 嗎 ?

******

SixLabors.Fonts 1.0.1

https://www.nuget.org/packages/SixLabors.Fonts/1.0.1

1.01支援 .NET Framework


SixLabors.Fonts 2.1.3

https://www.nuget.org/packages/SixLabors.Fonts/2.1.3

至少需要.NET 6.0,不支援 .NET Framework


SixLabors.Fonts 3.1.0

https://www.nuget.org/packages/SixLabors.Fonts/3.1.0

至少需要.NET 8.0,不支援 .NET Framework

(完)

2026年4月18日 星期六

[研究]比較NPOI和ClosedXML

[研究]比較NPOI和ClosedXML

2026-04-17

📊 核心差異比較

面向 NPOI ClosedXML
支援格式 ✅ .xls + .xlsx ❌ 只支援 .xlsx
API 易用性 ❌ 偏底層(像 Java POI) ✅ 很直覺、C#風格
開發速度 慢 快
功能完整度 高(含 Word / Excel) 主要專注 Excel
學習曲線 高 低
效能(大檔) 較穩定 有時較吃記憶體
授權 Apache 2.0 MIT
使用情境 舊系統整合 報表產生

📌 ClosedXML 是「包裝 OpenXML」,強調好寫

📌 NPOI 是「移植 Apache POI」,偏原始控制

(完)

2026年4月15日 星期三

[研究]ClosedXML 0.105.0 是否相依 System.ValueTuple 測試(二)

[研究]ClosedXML 0.105.0 是否相依 System.ValueTuple 測試(二)

2025-04-15

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

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

[研究]System.ValueTuple 4.5.0 升級到 4.6.x 後執行出錯
https://shaurong.blogspot.com/2026/04/systemvaluetuple-450-46x.html
根據這篇,ChatGPT 說 ClosedXML 0.105 在 Graphics engine 會強制載入 font engine,直接觸發 ValueTuple load chain

[研究]ClosedXML 0.105.0 是否相依 System.ValueTuple 測試
https://shaurong.blogspot.com/2026/04/closedxml-01050-systemvaluetuple.html
根據這篇,沒有 ValueTuple

此測試用 NuGet 多安裝了 System.ValueTuple 4.6.2

**********

packages.config


<?xml version="1.0" encoding="utf-8"?> <packages> <package id="ClosedXML" version="0.105.0" targetFramework="net48" /> <package id="ClosedXML.Parser" version="2.0.0" targetFramework="net48" /> <package id="DocumentFormat.OpenXml" version="3.5.1" targetFramework="net48" /> <package id="DocumentFormat.OpenXml.Framework" version="3.5.1" targetFramework="net48" /> <package id="ExcelNumberFormat" version="1.1.0" targetFramework="net48" /> <package id="Microsoft.Bcl.HashCode" version="6.0.0" targetFramework="net48" /> <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="4.1.0" targetFramework="net48" /> <package id="RBush.Signed" version="4.0.0" targetFramework="net48" /> <package id="SixLabors.Fonts" version="1.0.1" targetFramework="net48" /> <package id="System.Buffers" version="4.6.1" targetFramework="net48" /> <package id="System.Memory" version="4.6.3" targetFramework="net48" /> <package id="System.Numerics.Vectors" version="4.6.1" targetFramework="net48" /> <package id="System.Runtime.CompilerServices.Unsafe" version="6.1.2" targetFramework="net48" /> <package id="System.ValueTuple" version="4.6.2" targetFramework="net48" /> </packages>

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="btnExport" runat="server" Text="匯出 Excel" OnClick="btnExport_Click" /> </form> </body> </html>

Default.aspx.cs


using ClosedXML.Excel; using System; using System.Data; using System.IO; namespace WebApplication1 { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnExport_Click(object sender, EventArgs e) { // 建立測試資料 DataTable dt = GetSampleData(); using (XLWorkbook wb = new XLWorkbook()) { var ws = wb.Worksheets.Add(dt, "Sheet1"); // 設定樣式 ws.Columns().AdjustToContents(); ws.Row(1).Style.Font.Bold = true; // 輸出 Response.Clear(); Response.Buffer = true; Response.Charset = ""; Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", "attachment;filename=Export.xlsx"); using (MemoryStream ms = new MemoryStream()) { wb.SaveAs(ms); ms.WriteTo(Response.OutputStream); Response.Flush(); Response.End(); } } } private DataTable GetSampleData() { DataTable dt = new DataTable(); dt.Columns.Add("ID", typeof(int)); dt.Columns.Add("姓名", typeof(string)); dt.Columns.Add("日期", typeof(DateTime)); dt.Columns.Add("金額", typeof(decimal)); dt.Rows.Add(1, "王小明", DateTime.Now, 1000); dt.Rows.Add(2, "李小華", DateTime.Now.AddDays(-1), 2000); dt.Rows.Add(3, "陳小美", DateTime.Now.AddDays(-2), 3000); return dt; } } }

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

Deploy 後實際測試



執行時期沒有發生錯誤,看起來正常。
ClosedXML 0.105 在 Graphics engine 會強制載入 font engine,直接觸發 ValueTuple load chain 的情況,此測試中沒有發生,或是 ChatGPT 的說法有問題???

(完)

相關

2026年4月14日 星期二

[研究]ClosedXML 0.105.0 是否相依 System.ValueTuple 測試

[研究]ClosedXML 0.105.0 是否相依 System.ValueTuple 測試

2025-04-07

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

續這篇

[研究]System.ValueTuple 4.5.0 升級到 4.6.x 後執行出錯
https://shaurong.blogspot.com/2026/04/systemvaluetuple-450-46x.html

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

NuGet 安裝ClosedXML 0.105.0

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

WebApplication1

正在安裝:

DocumentFormat.OpenXml.Framework.3.1.1

DocumentFormat.OpenXml.3.1.1

ExcelNumberFormat.1.1.0

Microsoft.Bcl.HashCode.1.1.1

RBush.Signed.4.0.0

System.Buffers.4.5.1

System.Numerics.Vectors.4.5.0

System.Runtime.CompilerServices.Unsafe.4.7.0

System.Memory.4.5.5

ClosedXML.Parser.2.0.0

SixLabors.Fonts.1.0.0

ClosedXML.0.105.0

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

更新

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

WebApplication1

更新:

SixLabors.Fonts.1.0.0 -> SixLabors.Fonts.2.1.3

System.Memory.4.5.5 -> System.Memory.4.6.3

System.Runtime.CompilerServices.Unsafe.4.7.0 -> System.Runtime.CompilerServices.Unsafe.6.1.2

System.Numerics.Vectors.4.5.0 -> System.Numerics.Vectors.4.6.1

System.Buffers.4.5.1 -> System.Buffers.4.6.1

Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1 -> Microsoft.CodeDom.Providers.DotNetCompilerPlatform.4.1.0

Microsoft.Bcl.HashCode.1.1.1 -> Microsoft.Bcl.HashCode.6.0.0

DocumentFormat.OpenXml.3.1.1 -> DocumentFormat.OpenXml.3.5.1

DocumentFormat.OpenXml.Framework.3.1.1 -> DocumentFormat.OpenXml.Framework.3.5.1

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

下面,編譯失敗

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

嚴重性 程式碼 說明 專案 檔案 行 隱藏項目狀態

錯誤 無法安裝封裝 'SixLabors.Fonts 2.1.3'。您正嘗試將此封裝安裝到以 '.NETFramework,Version=v4.8' 為目標的專案,但該封裝不包含任何與架構相容的組件參考或內容檔。如需詳細資訊,請連絡封裝作者。

********************************************************************************
SixLabors.Fonts 2.1.3 不支援 .NET Framework 4.8(或沒有提供可用的 compatible assets)

********************************************************************************
不要升級 SixLabors.Fonts 2.1.3,其他再升級一次
********************************************************************************

WebApplication1

更新:

System.Memory.4.5.5 -> System.Memory.4.6.3

System.Runtime.CompilerServices.Unsafe.4.7.0 -> System.Runtime.CompilerServices.Unsafe.6.1.2

System.Numerics.Vectors.4.5.0 -> System.Numerics.Vectors.4.6.1

System.Buffers.4.5.1 -> System.Buffers.4.6.1

Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1 -> Microsoft.CodeDom.Providers.DotNetCompilerPlatform.4.1.0

Microsoft.Bcl.HashCode.1.1.1 -> Microsoft.Bcl.HashCode.6.0.0

DocumentFormat.OpenXml.3.1.1 -> DocumentFormat.OpenXml.3.5.1

DocumentFormat.OpenXml.Framework.3.1.1 -> DocumentFormat.OpenXml.Framework.3.5.1

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

packages.config


<?xml version="1.0" encoding="utf-8"?> <packages> <package id="ClosedXML" version="0.105.0" targetFramework="net48" /> <package id="ClosedXML.Parser" version="2.0.0" targetFramework="net48" /> <package id="DocumentFormat.OpenXml" version="3.5.1" targetFramework="net48" /> <package id="DocumentFormat.OpenXml.Framework" version="3.5.1" targetFramework="net48" /> <package id="ExcelNumberFormat" version="1.1.0" targetFramework="net48" /> <package id="Microsoft.Bcl.HashCode" version="6.0.0" targetFramework="net48" /> <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="4.1.0" targetFramework="net48" /> <package id="RBush.Signed" version="4.0.0" targetFramework="net48" /> <package id="SixLabors.Fonts" version="1.0.0" targetFramework="net48" /> <package id="System.Buffers" version="4.6.1" targetFramework="net48" /> <package id="System.Memory" version="4.6.3" targetFramework="net48" /> <package id="System.Numerics.Vectors" version="4.6.1" targetFramework="net48" /> <package id="System.Runtime.CompilerServices.Unsafe" version="6.1.2" targetFramework="net48" /> </packages>

並沒有用到  System.ValueTuple 

(完)

相關

2025年3月31日 星期一

[研究]哪個元件 OpenXML, ClosedXML, Aspose Cells, ExcelDataReader, NPOI 匯出成 .xlsx 會較省記憶體、較快?

[研究]哪個元件 OpenXML, ClosedXML, Aspose Cells, ExcelDataReader, NPOI 匯出成 .xlsx 會較省記憶體、較快?

2025-03-31

 ASP.NET, WebForm, 從 SQL Server 讀取20萬筆資料,用哪個元件 OpenXML, ClosedXML, Aspose Cells, ExcelDataReader, NPOI 匯出成 .xlsx 會較省記憶體、較快

ChatGPT 說:

在處理大量資料(如 20 萬筆資料)並將其匯出為 .xlsx 格式時,選擇合適的元件對於效能與記憶體使用至關重要。以下是你列出來的幾個元件的比較,根據記憶體消耗與效能來評估:

1. OpenXML SDK

  • 記憶體消耗:OpenXML 是處理 .xlsx 格式的底層 API,直接與 Excel 檔案結構互動,因此它的記憶體消耗相對較低。它不會加載整個工作簿進記憶體,而是逐步寫入檔案,因此適合處理大量資料。
  • 效能:效能相對較快,特別是在處理簡單的資料寫入時。它的低層級操作使其可以有效處理大量資料,而不會因為大量的記憶體消耗而產生效能瓶頸。
  • 缺點:操作上相對較為繁瑣,需手動處理各種 Excel 的細節(如格式化、資料填充等)。
  • 結論:如果記憶體消耗是主要考量,OpenXML SDK 是處理大量資料時效能最好且最省記憶體的選擇。

2. ClosedXML

  • 記憶體消耗:ClosedXML 會加載整個工作簿進記憶體,這意味著當處理大量資料時,它的記憶體消耗會比較高。對於 20 萬筆資料,記憶體消耗會比 OpenXML 高。
  • 效能:ClosedXML 提供高層次的 API,使得開發人員能夠快速上手,但它的效能在處理大型資料集時會受到記憶體限制。
  • 優點:API 使用簡單,開發過程中可以很容易地進行格式化和其他 Excel 特性設定。
  • 缺點:處理大型資料集時,記憶體消耗和效能可能會成為瓶頸。
  • 結論:如果開發速度和易用性比效能更重要,ClosedXML 是不錯的選擇,但在處理大量資料時記憶體消耗會較高。

3. Aspose.Cells

  • 記憶體消耗:Aspose.Cells 是一個商業元件,對於大型資料集的處理有很好的效能,記憶體消耗比 OpenXML 稍高,但仍然可以處理較大資料集。對於 20 萬筆資料,它的效能表現會較為穩定。
  • 效能:Aspose.Cells 提供非常豐富的功能和強大的性能,特別是在處理大型文件和複雜格式化時非常優秀。然而,它是商業授權的元件,會有額外成本。
  • 優點:功能強大,能夠處理複雜的格式、公式和圖表,並且效能較為穩定。
  • 缺點:商業授權,需支付費用。
  • 結論:如果需要高度功能性和穩定性,並且能夠接受商業授權的費用,Aspose.Cells 是一個很好的選擇,但對於 20 萬筆資料來說,記憶體消耗會相對較高。

4. ExcelDataReader

  • 記憶體消耗:ExcelDataReader 主要用於讀取 Excel 檔案,而不是寫入,它的記憶體消耗相對較低。它支援 .xlsx 格式的讀取,但並不直接支援寫入檔案,因此不適用於匯出資料。
  • 效能:效能快速,特別是在處理讀取 Excel 檔案時,但不適用於資料匯出。
  • 結論:ExcelDataReader 主要用於讀取資料,並不適用於從 SQL Server 匯出資料到 .xlsx 格式。

5. NPOI

  • 記憶體消耗:NPOI 在處理大型資料集時表現良好,它的記憶體消耗比 ClosedXML 要低,但會比 OpenXML 高一些。它不會加載整個工作簿到記憶體中,這使得它在記憶體消耗上比 ClosedXML 更有優勢。
  • 效能:效能相對較快,特別是當資料不需要複雜的格式化時。它的底層操作較為簡單,能夠有效處理大量資料,且記憶體消耗較為節省。
  • 缺點:API 相對較為底層,對於需要高階格式化和功能的需求,可能會顯得繁瑣。
  • 結論:NPOI 是一個不錯的選擇,特別是在需要低記憶體消耗的情況下,它在處理大量資料時表現不錯,且比 ClosedXML 更為輕量。

結論:

  • 最省記憶體且效能最佳:OpenXML SDK。這是處理大量資料時最節省記憶體並且效能最好的選擇。
  • 較簡單的高層次 API,效能較佳:NPOI。對於大量資料的匯出,它的記憶體消耗比 ClosedXML 低,並且效能也相對較好。
  • 需要高功能性(格式化、圖表等),且能接受費用:Aspose.Cells,但記憶體消耗會較高。
  • 如果你的主要關注點是處理 20 萬筆資料的效能與記憶體消耗,推薦使用 OpenXML SDK 或 NPOI,根據你的需求選擇適合的 API 層級。

(完)

[研究]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快。

(完)

相關

2024年10月11日 星期五

[研究]ASP.NET,DocumentFormat.OpenXml.2.20.0 升級 DocumentFormat.OpenXml.3.1.0 問題

[研究]ASP.NET,DocumentFormat.OpenXml.2.20.0 升級 DocumentFormat.OpenXml.3.1.0 問題

2024-10-11

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

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

如果是直接使用 OpenXml SDK (Open XML SDK, Open-XML-SDK) 語法,可能出錯;如果直接使用 ClosedXML 套件語法,可能不會有問題。

jobTitle = getOpenXMLSDKCellValue(workbookPart, (Cell)r.ChildElements.GetItem(0));

編譯出現錯誤

error CS1061: 'OpenXmlElementList' 未包含 'GetItem' 的定義,也找不到可接受類型 'OpenXmlElementList' 第一個引數的可存取擴充方法 'GetItem' (是否遺漏 using 指示詞或組件參考?)

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

實際測試,修該如下,編譯可以通過。
jobTitle = getOpenXMLSDKCellValue(workbookPart, (Cell)r.ChildElements[0]);   

(完)

相關

[研究]ASP.NET,ClosedXML 與 SixLabors.Fonts.相依套件測試

[研究]ASP.NET,ClosedXML 與 SixLabors.Fonts.相依套件測試

2024-10-11

NuGet 安裝 ClosedXML 104.1 時,會自動安裝 SixLabors.Fonts.1.0.0

SixLabors.Fonts.1.0.0 -> SixLabors.Fonts.2.0.4,

出現

錯誤 無法安裝封裝 'SixLabors.Fonts 2.0.4'。您正嘗試將此封裝安裝到以 '.NETFramework,Version=v4.8' 為目標的專案,但該封裝不包含任何與架構相容的組件參考或內容檔。如需詳細資訊,請連絡封裝作者。

這個專案就是 .NET Framework 4.8,SixLabors.Fonts 2.x 似乎不支援。


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

ClosedXML 0.102.3 也需要 SixLabors.Fonts.1.0.1




嚴重性 程式碼 說明 專案 檔案 行 隱藏項目狀態
錯誤 無法安裝封裝 'SixLabors.Fonts 2.0.4'。您正嘗試將此封裝安裝到以 '.NETFramework,Version=v4.8' 為目標的專案,但該封裝不包含任何與架構相容的組件參考或內容檔。如需詳細資訊,請連絡封裝作者。

SixLabors.Fonts 1.0.1 支援 .NET Core 3.1 和 .NET Standard 2.0

SixLabors.Fonts 2.0.4 支援 .NET 6.0

(完)

相關

2024年10月9日 星期三

[研究]ASP.NET,WebForm, NuGet安裝ClosedXML 0.104.1相依套件測試

[研究]ASP.NET,WebForm, NuGet安裝ClosedXML 0.104.1相依套件測試

2024-10-09

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

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

WebApplication1

正在安裝:

DocumentFormat.OpenXml.Framework.3.0.1

DocumentFormat.OpenXml.3.0.1

ExcelNumberFormat.1.1.0

Microsoft.Bcl.HashCode.1.1.1

Microsoft.NETCore.Platforms.1.1.0

Microsoft.Win32.Primitives.4.3.0

System.AppContext.4.3.0

System.Buffers.4.5.1

System.Collections.4.3.0

System.Collections.Concurrent.4.3.0

System.Console.4.3.0

System.Diagnostics.Debug.4.3.0

System.Diagnostics.DiagnosticSource.4.3.0

System.Diagnostics.Tools.4.3.0

System.Diagnostics.Tracing.4.3.0

System.Globalization.4.3.0

System.Globalization.Calendars.4.3.0

System.IO.4.3.0

System.IO.Compression.4.3.0

System.IO.Compression.ZipFile.4.3.0

System.IO.FileSystem.Primitives.4.3.0

System.IO.FileSystem.4.3.0

System.IO.Packaging.8.0.0

System.Linq.4.3.0

System.Linq.Expressions.4.3.0

System.Net.Primitives.4.3.0

System.Net.Sockets.4.3.0

System.Numerics.Vectors.4.5.0

System.ObjectModel.4.3.0

System.Reflection.4.3.0

System.Reflection.Extensions.4.3.0

System.Reflection.Primitives.4.3.0

System.Resources.ResourceManager.4.3.0

System.Runtime.4.3.0

System.Runtime.CompilerServices.Unsafe.4.7.0

System.Memory.4.5.4

ClosedXML.Parser.1.2.0

SixLabors.Fonts.1.0.0

System.Runtime.Extensions.4.3.0

System.Runtime.Handles.4.3.0

System.Runtime.InteropServices.4.3.0

System.Runtime.InteropServices.RuntimeInformation.4.3.0

System.Runtime.Numerics.4.3.0

System.Security.Cryptography.Encoding.4.3.0

System.Security.Cryptography.Primitives.4.3.0

System.Security.Cryptography.Algorithms.4.3.0

System.Security.Cryptography.X509Certificates.4.3.0

System.Net.Http.4.3.0

System.Text.Encoding.4.3.0

System.Text.Encoding.Extensions.4.3.0

System.Text.RegularExpressions.4.3.0

System.Threading.4.3.0

System.Threading.Tasks.4.3.0

System.Threading.Timer.4.3.0

System.Xml.ReaderWriter.4.3.0

System.Xml.XDocument.4.3.0

NETStandard.Library.1.6.1

RBush.3.2.0

ClosedXML.0.104.1

成功

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

再次更新

WebApplication1

更新:

NETStandard.Library.1.6.1 -> NETStandard.Library.2.0.3

System.Xml.ReaderWriter.4.3.0 -> System.Xml.ReaderWriter.4.3.1

System.Text.RegularExpressions.4.3.0 -> System.Text.RegularExpressions.4.3.1

System.Net.Http.4.3.0 -> System.Net.Http.4.3.4

System.Security.Cryptography.X509Certificates.4.3.0 -> System.Security.Cryptography.X509Certificates.4.3.2

System.Security.Cryptography.Algorithms.4.3.0 -> System.Security.Cryptography.Algorithms.4.3.1

System.Runtime.Extensions.4.3.0 -> System.Runtime.Extensions.4.3.1

SixLabors.Fonts.1.0.0 -> SixLabors.Fonts.2.0.4

System.Memory.4.5.4 -> System.Memory.4.5.5

System.Runtime.CompilerServices.Unsafe.4.7.0 -> System.Runtime.CompilerServices.Unsafe.6.0.0

System.Runtime.4.3.0 -> System.Runtime.4.3.1

System.Net.Primitives.4.3.0 -> System.Net.Primitives.4.3.1

System.IO.Packaging.8.0.0 -> System.IO.Packaging.8.0.1

System.Diagnostics.DiagnosticSource.4.3.0 -> System.Diagnostics.DiagnosticSource.8.0.1

System.Console.4.3.0 -> System.Console.4.3.1

Microsoft.NETCore.Platforms.1.1.0 -> Microsoft.NETCore.Platforms.7.0.4

Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1 -> Microsoft.CodeDom.Providers.DotNetCompilerPlatform.4.1.0

DocumentFormat.OpenXml.3.0.1 -> DocumentFormat.OpenXml.3.1.0

DocumentFormat.OpenXml.Framework.3.0.1 -> DocumentFormat.OpenXml.Framework.3.1.0

出現

嚴重性 程式碼 說明 專案 檔案 行 隱藏項目狀態

錯誤 無法安裝封裝 'SixLabors.Fonts 2.0.4'。您正嘗試將此封裝安裝到以 '.NETFramework,Version=v4.8' 為目標的專案,但該封裝不包含任何與架構相容的組件參考或內容檔。如需詳細資訊,請連絡封裝作者。

但是這個專案就是 4.8 啊?


********************************************************************************
把 SixLabors.Fonts 勾選取消,再一次


WebApplication1

更新:

NETStandard.Library.1.6.1 -> NETStandard.Library.2.0.3
System.Xml.ReaderWriter.4.3.0 -> System.Xml.ReaderWriter.4.3.1
System.Text.RegularExpressions.4.3.0 -> System.Text.RegularExpressions.4.3.1
System.Net.Http.4.3.0 -> System.Net.Http.4.3.4
System.Security.Cryptography.X509Certificates.4.3.0 -> System.Security.Cryptography.X509Certificates.4.3.2
System.Security.Cryptography.Algorithms.4.3.0 -> System.Security.Cryptography.Algorithms.4.3.1
System.Runtime.Extensions.4.3.0 -> System.Runtime.Extensions.4.3.1
System.Memory.4.5.4 -> System.Memory.4.5.5
System.Runtime.CompilerServices.Unsafe.4.7.0 -> System.Runtime.CompilerServices.Unsafe.6.0.0
System.Runtime.4.3.0 -> System.Runtime.4.3.1
System.Net.Primitives.4.3.0 -> System.Net.Primitives.4.3.1
System.IO.Packaging.8.0.0 -> System.IO.Packaging.8.0.1
System.Diagnostics.DiagnosticSource.4.3.0 -> System.Diagnostics.DiagnosticSource.8.0.1
System.Console.4.3.0 -> System.Console.4.3.1
Microsoft.NETCore.Platforms.1.1.0 -> Microsoft.NETCore.Platforms.7.0.4
Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1 -> Microsoft.CodeDom.Providers.DotNetCompilerPlatform.4.1.0
DocumentFormat.OpenXml.3.0.1 -> DocumentFormat.OpenXml.3.1.0
DocumentFormat.OpenXml.Framework.3.0.1 -> DocumentFormat.OpenXml.Framework.3.1.0

嚴重性 程式碼 說明 專案 檔案 行 隱藏項目狀態
錯誤 由於另一個處理序正在使用檔案 'C:\CodeTemp6\WebApplication1\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.4.1.0\tasks/DotNetCompilerPlatformTasks.dll',所以無法存取該檔案。


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

再次


WebApplication1

更新:

NETStandard.Library.1.6.1 -> NETStandard.Library.2.0.3

System.Xml.ReaderWriter.4.3.0 -> System.Xml.ReaderWriter.4.3.1

System.Text.RegularExpressions.4.3.0 -> System.Text.RegularExpressions.4.3.1

System.Net.Http.4.3.0 -> System.Net.Http.4.3.4

System.Security.Cryptography.X509Certificates.4.3.0 -> System.Security.Cryptography.X509Certificates.4.3.2

System.Security.Cryptography.Algorithms.4.3.0 -> System.Security.Cryptography.Algorithms.4.3.1

System.Runtime.Extensions.4.3.0 -> System.Runtime.Extensions.4.3.1

System.Memory.4.5.4 -> System.Memory.4.5.5

System.Runtime.CompilerServices.Unsafe.4.7.0 -> System.Runtime.CompilerServices.Unsafe.6.0.0

System.Runtime.4.3.0 -> System.Runtime.4.3.1

System.Net.Primitives.4.3.0 -> System.Net.Primitives.4.3.1

System.IO.Packaging.8.0.0 -> System.IO.Packaging.8.0.1

System.Diagnostics.DiagnosticSource.4.3.0 -> System.Diagnostics.DiagnosticSource.8.0.1

System.Console.4.3.0 -> System.Console.4.3.1

Microsoft.NETCore.Platforms.1.1.0 -> Microsoft.NETCore.Platforms.7.0.4

Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1 -> Microsoft.CodeDom.Providers.DotNetCompilerPlatform.4.1.0

DocumentFormat.OpenXml.3.0.1 -> DocumentFormat.OpenXml.3.1.0

DocumentFormat.OpenXml.Framework.3.0.1 -> DocumentFormat.OpenXml.Framework.3.1.0

成功

最後只剩下

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

packages.config 內容

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="ClosedXML" version="0.104.1" targetFramework="net48" />
  <package id="ClosedXML.Parser" version="1.2.0" targetFramework="net48" />
  <package id="DocumentFormat.OpenXml" version="3.1.0" targetFramework="net48" />
  <package id="DocumentFormat.OpenXml.Framework" version="3.1.0" targetFramework="net48" />
  <package id="ExcelNumberFormat" version="1.1.0" targetFramework="net48" />
  <package id="Microsoft.Bcl.HashCode" version="1.1.1" targetFramework="net48" />
  <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="4.1.0" targetFramework="net48" />
  <package id="Microsoft.NETCore.Platforms" version="7.0.4" targetFramework="net48" />
  <package id="Microsoft.Win32.Primitives" version="4.3.0" targetFramework="net48" />
  <package id="NETStandard.Library" version="2.0.3" targetFramework="net48" />
  <package id="RBush" version="3.2.0" targetFramework="net48" />
  <package id="SixLabors.Fonts" version="1.0.0" targetFramework="net48" />
  <package id="System.AppContext" version="4.3.0" targetFramework="net48" />
  <package id="System.Buffers" version="4.5.1" targetFramework="net48" />
  <package id="System.Collections" version="4.3.0" targetFramework="net48" />
  <package id="System.Collections.Concurrent" version="4.3.0" targetFramework="net48" />
  <package id="System.Console" version="4.3.1" targetFramework="net48" />
  <package id="System.Diagnostics.Debug" version="4.3.0" targetFramework="net48" />
  <package id="System.Diagnostics.DiagnosticSource" version="8.0.1" targetFramework="net48" />
  <package id="System.Diagnostics.Tools" version="4.3.0" targetFramework="net48" />
  <package id="System.Diagnostics.Tracing" version="4.3.0" targetFramework="net48" />
  <package id="System.Globalization" version="4.3.0" targetFramework="net48" />
  <package id="System.Globalization.Calendars" version="4.3.0" targetFramework="net48" />
  <package id="System.IO" version="4.3.0" targetFramework="net48" />
  <package id="System.IO.Compression" version="4.3.0" targetFramework="net48" />
  <package id="System.IO.Compression.ZipFile" version="4.3.0" targetFramework="net48" />
  <package id="System.IO.FileSystem" version="4.3.0" targetFramework="net48" />
  <package id="System.IO.FileSystem.Primitives" version="4.3.0" targetFramework="net48" />
  <package id="System.IO.Packaging" version="8.0.1" targetFramework="net48" />
  <package id="System.Linq" version="4.3.0" targetFramework="net48" />
  <package id="System.Linq.Expressions" version="4.3.0" targetFramework="net48" />
  <package id="System.Memory" version="4.5.5" targetFramework="net48" />
  <package id="System.Net.Http" version="4.3.4" targetFramework="net48" />
  <package id="System.Net.Primitives" version="4.3.1" targetFramework="net48" />
  <package id="System.Net.Sockets" version="4.3.0" targetFramework="net48" />
  <package id="System.Numerics.Vectors" version="4.5.0" targetFramework="net48" />
  <package id="System.ObjectModel" version="4.3.0" targetFramework="net48" />
  <package id="System.Reflection" version="4.3.0" targetFramework="net48" />
  <package id="System.Reflection.Extensions" version="4.3.0" targetFramework="net48" />
  <package id="System.Reflection.Primitives" version="4.3.0" targetFramework="net48" />
  <package id="System.Resources.ResourceManager" version="4.3.0" targetFramework="net48" />
  <package id="System.Runtime" version="4.3.1" targetFramework="net48" />
  <package id="System.Runtime.CompilerServices.Unsafe" version="6.0.0" targetFramework="net48" />
  <package id="System.Runtime.Extensions" version="4.3.1" targetFramework="net48" />
  <package id="System.Runtime.Handles" version="4.3.0" targetFramework="net48" />
  <package id="System.Runtime.InteropServices" version="4.3.0" targetFramework="net48" />
  <package id="System.Runtime.InteropServices.RuntimeInformation" version="4.3.0" targetFramework="net48" />
  <package id="System.Runtime.Numerics" version="4.3.0" targetFramework="net48" />
  <package id="System.Security.Cryptography.Algorithms" version="4.3.1" targetFramework="net48" />
  <package id="System.Security.Cryptography.Encoding" version="4.3.0" targetFramework="net48" />
  <package id="System.Security.Cryptography.Primitives" version="4.3.0" targetFramework="net48" />
  <package id="System.Security.Cryptography.X509Certificates" version="4.3.2" targetFramework="net48" />
  <package id="System.Text.Encoding" version="4.3.0" targetFramework="net48" />
  <package id="System.Text.Encoding.Extensions" version="4.3.0" targetFramework="net48" />
  <package id="System.Text.RegularExpressions" version="4.3.1" targetFramework="net48" />
  <package id="System.Threading" version="4.3.0" targetFramework="net48" />
  <package id="System.Threading.Tasks" version="4.3.0" targetFramework="net48" />
  <package id="System.Threading.Timer" version="4.3.0" targetFramework="net48" />
  <package id="System.Xml.ReaderWriter" version="4.3.1" targetFramework="net48" />
  <package id="System.Xml.XDocument" version="4.3.0" targetFramework="net48" />
</packages>


相依套件頗多的,比較重要是 DocumentFormat.OpenXml,而且必須是 3.x 版才行。

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

額外補充




嚴重性 程式碼 說明 專案 檔案 行 隱藏項目狀態
錯誤 無法安裝封裝 'SixLabors.Fonts 2.0.4'。您正嘗試將此封裝安裝到以 '.NETFramework,Version=v4.8' 為目標的專案,但該封裝不包含任何與架構相容的組件參考或內容檔。如需詳細資訊,請連絡封裝作者。

SixLabors.Fonts 1.0.1 支援 .NET Core 3.1 和 .NET Standard 2.0

SixLabors.Fonts 2.0.4 支援 .NET 6.0

(完)

相關

2024年3月29日 星期五

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

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

2024-03-29

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

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

延續下面,但改用 DataTable,而非把資料逐一放入 ws.Cell 儲存格中

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

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

<!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:SqlDataSource ID="SqlDataSource_Field2" runat="server"
            ConnectionString="<%$ ConnectionStrings:MyDBConnectionString %>"
            SelectCommand="SELECT N'全部' AS [Field2], 0 AS Priority
            UNION
            SELECT DISTINCT [Field2], 1 AS Priority FROM [MyTable] ORDER BY Priority, [Field2]"></asp:SqlDataSource>
        <asp:DropDownList ID="DropDownList_Field2" runat="server"
            AutoPostBack="True" DataSourceID="SqlDataSource_Field2"
            DataTextField="Field2" DataValueField="Field2">
        </asp:DropDownList>
        <br />
        <asp:Button ID="Button_Export_Xlsx_By_ClosedXML" runat="server" Text="匯出(.xlsx)"
            OnClick="Button_Export_Xlsx_By_ClosedXML_Click" /><br />
        <asp:Label ID="Label_MSG1" runat="server" Text="Label"></asp:Label>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:MyDBConnectionString %>"
            SelectCommand="--TSQL--
            SELECT * FROM [MyTable]
            WHERE ([Field2]=@Filed2 OR @Filed2=N'全部');">
            <SelectParameters>
                <asp:ControlParameter ControlID="DropDownList_Field2" Name="Filed2" PropertyName="SelectedValue" />
            </SelectParameters>
        </asp:SqlDataSource>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="SN" DataSourceID="SqlDataSource1">
            <Columns>
                <asp:BoundField DataField="SN" HeaderText="SN" InsertVisible="False" ReadOnly="True" SortExpression="SN" />
                <asp:BoundField DataField="Field1" HeaderText="Field1" SortExpression="Field1" />
                <asp:BoundField DataField="Field2" HeaderText="Field2" SortExpression="Field2" />
            </Columns>
        </asp:GridView>

    </form>
</body>
</html>



Default.aspx.cs
using ClosedXML.Excel;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Configuration;

namespace WebApplication1
{
    public partial class Default2 : 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 = { "SN", "Field1", "Field2" };
                    // 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 [MyTable]
";
                    DataTable dataTable = new DataTable();
                    using (SqlConnection connection = new SqlConnection(
                        WebConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString))
                    {
                        SqlCommand command = new SqlCommand(queryString, connection);
                        command.Parameters.Clear();
                        command.Parameters.AddWithValue("@Field2", DropDownList_Field2.SelectedValue);
                        connection.Open();

                        SqlDataAdapter adapter = new SqlDataAdapter(command);
                        adapter.Fill(dataTable);

                        //var ws = wb.Worksheets.Add(dataTable, WorksheetName);
                        ws.Cell(2, 1).InsertData(dataTable.AsEnumerable());

                        //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();
                        string endCell = "C" + (dataTable.Columns.Count+1);
                        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>");
            }
        }
        // ----------
    }
}

測試成功



(完)

相關

[研究]ASP.NET,WebForm,使用 ClosedXML 0.102.2 匯出、寫入 .xlsx(暫存、不暫存檔)
https://shaurong.blogspot.com/2024/03/aspnetwebform-closedxml-01022-xlsx.html

[研究][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



2024年1月22日 星期一

[研究][ASP.NET]ClosedXML 匯入 .xlsx 出現Anonymous_Sheet_DB 問題

[研究][ASP.NET]ClosedXML 匯入 .xlsx 出現Anonymous_Sheet_DB 問題

2024-01-21

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

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

ClosedXML.0.102.2 相依下面套件

DocumentFormat.OpenXml.2.16.0

ExcelNumberFormat.1.1.0

Irony.NetCore.1.0.11

System.Buffers.4.5.1

System.IO.4.3.0

System.IO.Packaging.6.0.0

System.Numerics.Vectors.4.5.0

System.Runtime.4.3.0

System.Runtime.CompilerServices.Unsafe.4.7.0

System.Memory.4.5.4

SixLabors.Fonts.1.0.0

System.Security.Cryptography.Encoding.4.3.0

System.Security.Cryptography.Primitives.4.3.0

System.Security.Cryptography.Algorithms.4.3.0

System.Security.Cryptography.X509Certificates.4.3.0

System.Net.Http.4.3.4

System.Text.RegularExpressions.4.3.1

XLParser.1.5.2

ClosedXML.0.102.2

其中 DocumentFormat.OpenXml 是微軟提供,它底下沒有相依套件,可以存取 Excel 檔案內容。雖然理論上和 Excel 軟體應該100%相容,但畢竟數十或上百 MB 的套件 (元件) 和數 GB 的 MS-Office 是無法相比的,所以 Excel 開啟看似正常,DocumentFormat.OpenXml 可能會無法讀取。

若使用非 Microsoft 提供的 .xlsx 存取元件,有相容問題的機率更高。

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

ASP.NET + WebForm, 使用 ClosedXML 匯入 .xlsx 檔案,var  firstCell = workSheet.FirstCellUsed(); 出現 Anonymous_Sheet_DB 問題? 

ChatGPT

根據你提供的資訊,出現 "Anonymous_Sheet_DB" 問題的原因可能是由於 ClosedXML 在讀取 Excel 檔案時遇到匿名工作表(Anonymous Sheet)的情況。匿名工作表通常是指沒有明確命名的工作表。

在 ClosedXML 中,FirstCellUsed() 方法用於找到工作表中的第一個被使用的儲存格,但如果該儲存格位於匿名工作表上,可能會導致問題。

以下是一些可能的解決方案:

  • 確保工作表有明確的名稱:

打開 Excel 檔案,確保所有的工作表都有一個明確的名稱。你可以透過右鍵點擊標籤進行重命名。確保使用 FirstCellUsed() 方法之前先確認該工作表是否具有名稱。

  • 嘗試使用 FirstCell() 方法:

而不是使用 FirstCellUsed(),你可以嘗試使用 FirstCell() 方法,它將返回工作表的第一個儲存格,而不檢查是否被使用。

IXLCell firstCell = workSheet.FirstCell();  

  • 更新 ClosedXML 版本:

確保你使用的是最新版本的 ClosedXML。有時庫的更新可能包含對這類問題的修復。

  • 處理匿名工作表的特殊情況:

如果你確定匿名工作表可能是問題所在,可以在程式碼中添加一些邏輯,處理匿名工作表的情況,例如跳過或額外處理。

請嘗試上述解決方案,看看是否有助於解決你遇到的問題。如果問題仍然存在,建議檢查 ClosedXML 的 GitHub 存儲庫或相關社群,以尋求更多協助或檢視是否有相關的更新和修復。

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

User

要把 Excel 的 A3 設定給 firstCell 該如何寫 ?

ChatGPT

在 ClosedXML 中,你可以使用 Cell 方法和儲存格的參考來設定 firstCell 為 A3 的儲存格。以下是相應的程式碼:

using ClosedXML.Excel;

// 假設你已經載入了一個工作簿,並且有一個工作表
IXLWorksheet workSheet = yourWorkbook.Worksheet(1);

// 設定 firstCell 為 A3 的儲存格
IXLCell firstCell = workSheet.Cell("A3");

// 讀取儲存格的值
var cellValue = firstCell.Value;

// 寫入新的值到儲存格
firstCell.Value = "New Value";

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

如何指定 ClosedXML 使用 "工作表1" 的 Worksheet ? 這樣可以避免 Anonymous Sheet 嗎 ?

ChatGPT

在 ClosedXML 中,你可以通過指定工作表的名稱來確保你正在使用正確的工作表,並避免匿名工作表的問題。以下是一個例子:

using ClosedXML.Excel;

// 假設你已經載入了一個工作簿,並且你知道工作表的名稱是 "工作表1"
IXLWorksheet workSheet = yourWorkbook.Worksheet("工作表1");

// 現在你可以在 workSheet 上進行操作,而不用擔心匿名工作表的問題

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

(完)

相關

2023年12月22日 星期五

[研究][ASP.NET]ClosedXML 的 OpenXml 從 2.20.0 升級 3.0.0 成功,執行失敗

[研究][ASP.NET]ClosedXML 的 OpenXml 從 2.20.0 升級 3.0.0 成功,執行失敗

[研究][ASP.NET]找不到方法: 'DocumentFormat.OpenXml.OpenXmlElementList DocumentFormat.OpenXml.OpenXmlElement.get_ChildElements()'。

2023-12-22、2024-02-26更新

環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C# + ClosedXML

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

(下圖) Click 可看 100% 圖

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

'/' 應用程式中發生伺服器錯誤。

找不到方法: 'DocumentFormat.OpenXml.OpenXmlElementList DocumentFormat.OpenXml.OpenXmlElement.get_ChildElements()'。

描述: 在執行目前 Web 要求的過程中發生未處理的例外狀況。請檢閱堆疊追蹤以取得錯誤的詳細資訊,以及在程式碼中產生的位置。

例外狀況詳細資訊: System.MissingMethodException: 找不到方法: 'DocumentFormat.OpenXml.OpenXmlElementList DocumentFormat.OpenXml.OpenXmlElement.get_ChildElements()'。

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

Method not found: 'DocumentFormat.OpenXml.OpenXmlElementList DocumentFormat.OpenXml.OpenXmlElement.get_ChildElements()'. #1608
https://github.com/dotnet/Open-XML-SDK/issues/1608

Migration to v3.0.0
https://learn.microsoft.com/en-us/office/open-xml/migration/migrate-v2-to-v3

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

參考

https://github.com/dotnet/Open-XML-SDK/issues/1608

實際測試發現是 NuGet 把 DocumentFormat.OpenXml 從 2.20.0 升級到 3.0.0 後發生問題, DocumentFormat.OpenXml.Framework 可以維持 3.0.0,不放心就一起也降到 2.20.0

檢查 packages.config 可知目前版本,

  <package id="DocumentFormat.OpenXml" version="3.0.0" targetFramework="net48" />
  <package id="DocumentFormat.OpenXml.Framework" version="3.0.0" targetFramework="net48" />

降版後是

  <package id="DocumentFormat.OpenXml" version="2.20.0" targetFramework="net48" />
  <package id="DocumentFormat.OpenXml.Framework" version="2.20.0" targetFramework="net48" />

實際測試,把 DocumentFormat.OpenXml.Framework 移除也正常運作。

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

請問 DocumentFormat.OpenXml 和 DocumentFormat.OpenXml.Framework 套件差異,後者必須存在嗎 ?

ChatGPT

截至我最後一次更新知識庫的時間(2022年1月),並沒有關於DocumentFormat.OpenXml.Framework的明確資訊。然而,根據我了解的情況,DocumentFormat.OpenXml是一個用於處理Office文件(如Word、Excel和PowerPoint)的.NET程式庫,而DocumentFormat.OpenXml.Framework則可能是一個與OpenXml相關的框架或工具集。

如果你遇到DocumentFormat.OpenXml.Framework的問題,建議檢查官方文檔或相關資源,以獲得最新的資訊。通常來說,開發人員使用DocumentFormat.OpenXml來處理Open XML文件,而Framework可能是一些附加的工具或支援額外功能的套件。確保查閱官方文檔以確定如何正確使用這些套件。

請注意,.NET生態系統中的套件和工具可能會經常更新,因此建議查看官方文檔或相關社群以獲取最新的資訊。

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

Open XML SDK 的最近更新
[3.0.0] - 2023-11-15
https://learn.microsoft.com/zh-cn/office/open-xml/what-s-new-in-the-open-xml-sdk
https://learn.microsoft.com/zh-tw/office/open-xml/what-s-new-in-the-open-xml-sdk

  • 核心基礎結構現在包含在新的套件DocumentFormat.OpenXml.Framework 中。類型化類別仍位於DocumentFormat.OpenXml 中。這意味著,可以引用DocumentFormat.OpenXml,但仍編譯相同的類型,但如果想要較小的套件,可以只依賴框架包。
  • 減少了DocumentFormat.OpenXml.Framework (#1471) 以外的套件的不必要的目標框架

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

2024-02-26 補

想要測試撰寫 ClosedXML 0.102.2 + DocumentFormat.OpenXml 3.0.0 的程式,發現 NuGet 安裝 ClosedXML 0.102.2 最新版,預設搭配 DocumentFormat.OpenXml 2.16.0,升級到 3.0.0 或 3.0.1 時,被禁止了。去年底是可以升級,但是執行時會失敗;現在直接禁止升級,算是省了麻煩。

嚴重性 程式碼 說明 專案 檔案 行 隱藏項目狀態

錯誤 無法解析相依性。'DocumentFormat.OpenXml 3.0.1' 與 'ClosedXML 0.102.2 條件約束: DocumentFormat.OpenXml (>= 2.16.0 && < 3.0.0)' 不相容。


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

(完)

相關


2023年4月14日 星期五

[研究]ASP.NET WebForm,ClosedXML 匯出 .xlsx 出錯:無法載入檔案或組件 'Irony

[研究]ASP.NET WebForm,ClosedXML 匯出 .xlsx 出錯:無法載入檔案或組件 'Irony

2023-04-14

使用的套件是 ClosedXML,但匯入 .xlsx 檔案出錯了。

無法載入檔案或組件 'Irony, Version=1.0.11.0, Culture=neutral, PublicKeyToken=ca48ace7223ead47' 或其相依性的其中之一。 找到的組件資訊清單定義與組件參考不符。 (發生例外狀況於 HRESULT: 0x80131040)

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

把 packages.config 中 Irony 那行砍了,NuGet 重新安裝、編譯、發佈,依舊錯誤,

想移除,被相依

嚴重性 程式碼 說明 專案 檔案 行 隱藏項目狀態

錯誤 因為 'XLParser.1.6.3' 相依於它,所以無法解除安裝 'Irony.NetCore.1.1.11'。


[研究]ASP.NET WebForm,安裝 ClosedXML 0.101.0相依套件測試

[研究]ASP.NET WebForm,安裝 ClosedXML 0.97 相依套件測試

測試2篇,想改用舊版 ClosedXML,捨棄 Irony 看來不容易。

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

最後把 .xlsx 用 Excel 另存成 .csv,關閉 Excel。
用 Excel 把 .csv 另存成新的 .xlsx,關閉 Excel。
新的 .xlsx 拿去使用,成功了。

.csv 是純文字檔案,存成它可以盡量避免和移除一些 .xlsx 中額外的資訊或格式,而 ClosedXML 無法處理的。

(完)

相關

[研究]ASP.NET WebForm,ClosedXML 匯出 .xlsx 出錯:無法載入檔案或組件 'Irony

[研究]ASP.NET WebForm,安裝 ClosedXML 0.101.0相依套件測試

[研究]ASP.NET WebForm,安裝 ClosedXML 0.97 相依套件測試

[研究]ASP.NET WebForm,安裝 ClosedXML 0.101.0相依套件測試

[研究]ASP.NET WebForm,安裝 ClosedXML 0.101.0相依套件測試

2023-04-13

環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C#

因為 ClosedXML 匯入功能癱瘓了,編譯、發佈都 OK,執行出現下面錯誤

無法載入檔案或組件 'Irony, Version=1.0.11.0, Culture=neutral, PublicKeyToken=ca48ace7223ead47' 或其相依性的其中之一。 找到的組件資訊清單定義與組件參考不符。 (發生例外狀況於 HRESULT: 0x80131040)

移除 Irony 失敗,packages.config 中註解掉 Irony 那行,編譯、發佈都 OK,執行仍錯誤,故另建專案,測試安裝一下最新版 ClosedXML 0.101.0,看看相依狀況。

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

packages.config 原本只有

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

NuGet 安裝 ClosedXML

嚴重性 程式碼 說明 專案 檔案 行 隱藏項目狀態

錯誤 無法解析相依性 'SixLabors.Fonts'。已使用來源: 'nuget.org', 'Microsoft Visual Studio Offline Packages'。

勾選「包括搶鮮版」,單獨先安裝 SixLabors.Fonts

WebApplication1

正在安裝:

System.Buffers.4.5.1

System.IO.Compression.4.3.0

System.IO.FileSystem.Primitives.4.3.0

System.IO.UnmanagedMemoryStream.4.3.0

System.Numerics.Vectors.4.5.0

System.Runtime.CompilerServices.Unsafe.4.7.0

System.Memory.4.5.4

System.Threading.Tasks.Parallel.4.3.0

System.ValueTuple.4.5.0

SixLabors.Fonts.1.0.0-beta19

取消勾選「包括搶鮮版」,安裝 ClosedXML

WebApplication1

正在安裝:

DocumentFormat.OpenXml.2.16.0

ExcelNumberFormat.1.1.0

Irony.NetCore.1.0.11

System.IO.Packaging.6.0.0

XLParser.1.5.2

ClosedXML.0.101.0

點「更新」頁籤,勾選「選取所有封裝」,按下「更新」按鈕

WebApplication1

更新:

XLParser.1.5.2 -> XLParser.1.6.3

System.Memory.4.5.4 -> System.Memory.4.5.5

System.Runtime.CompilerServices.Unsafe.4.7.0 -> System.Runtime.CompilerServices.Unsafe.7.0.0-preview.2.22152.2

System.IO.Packaging.6.0.0 -> System.IO.Packaging.8.0.0-preview.3.23174.8

Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1 -> Microsoft.CodeDom.Providers.DotNetCompilerPlatform.4.1.0

Irony.NetCore.1.0.11 -> Irony.NetCore.1.1.11

DocumentFormat.OpenXml.2.16.0 -> DocumentFormat.OpenXml.2.20.0

正在安裝:

System.Reflection.Emit.ILGeneration.4.3.0

System.Reflection.Emit.Lightweight.4.3.0

點「更新」頁籤,勾選「選取所有封裝」,按下「更新」按鈕

WebApplication1

更新:

System.Reflection.Emit.Lightweight.4.3.0 -> System.Reflection.Emit.Lightweight.4.7.0

System.Reflection.Emit.ILGeneration.4.3.0 -> System.Reflection.Emit.ILGeneration.4.7.0

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

packages.config 內容

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="ClosedXML" version="0.101.0" targetFramework="net48" />
  <package id="DocumentFormat.OpenXml" version="2.20.0" targetFramework="net48" />
  <package id="ExcelNumberFormat" version="1.1.0" targetFramework="net48" />
  <package id="Irony.NetCore" version="1.1.11" targetFramework="net48" />
  <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="4.1.0" targetFramework="net48" />
  <package id="SixLabors.Fonts" version="1.0.0-beta19" targetFramework="net48" />
  <package id="System.Buffers" version="4.5.1" targetFramework="net48" />
  <package id="System.IO.Compression" version="4.3.0" targetFramework="net48" />
  <package id="System.IO.FileSystem.Primitives" version="4.3.0" targetFramework="net48" />
  <package id="System.IO.Packaging" version="8.0.0-preview.3.23174.8" targetFramework="net48" />
  <package id="System.IO.UnmanagedMemoryStream" version="4.3.0" targetFramework="net48" />
  <package id="System.Memory" version="4.5.5" targetFramework="net48" />
  <package id="System.Numerics.Vectors" version="4.5.0" targetFramework="net48" />
  <package id="System.Reflection.Emit.ILGeneration" version="4.7.0" targetFramework="net48" />
  <package id="System.Reflection.Emit.Lightweight" version="4.7.0" targetFramework="net48" />
  <package id="System.Runtime.CompilerServices.Unsafe" version="7.0.0-preview.2.22152.2" targetFramework="net48" />
  <package id="System.Threading.Tasks.Parallel" version="4.3.0" targetFramework="net48" />
  <package id="System.ValueTuple" version="4.5.0" targetFramework="net48" />
  <package id="XLParser" version="1.6.3" targetFramework="net48" />
</packages>

(完)

相關


[研究]ASP.NET WebForm,ClosedXML 匯出 .xlsx 出錯:無法載入檔案或組件 'Irony

[研究]ASP.NET WebForm,安裝 ClosedXML 0.101.0相依套件測試

[研究]ASP.NET WebForm,安裝 ClosedXML 0.97 相依套件測試

[研究]ASP.NET WebForm,安裝 ClosedXML 0.97 相依套件測試

[研究]ASP.NET WebForm,安裝 ClosedXML 0.97 相依套件測試

2023-04-13

環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C#

因為 ClosedXML 匯入功能癱瘓了,編譯、發佈都 OK,執行出現下面錯誤

無法載入檔案或組件 'Irony, Version=1.0.11.0, Culture=neutral, PublicKeyToken=ca48ace7223ead47' 或其相依性的其中之一。 找到的組件資訊清單定義與組件參考不符。 (發生例外狀況於 HRESULT: 0x80131040)

移除 Irony 失敗,packages.config 中註解掉 Irony 那行,編譯、發佈都 OK,執行仍錯誤,故另建專案,測試安裝一下 0.9x 的最新版 ClosedXML 0.97,看看相依狀況,是否會用到 Irony

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

packages.config 原本只有

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

NuGet 安裝 ClosedXML

嚴重性 程式碼 說明 專案 檔案 行 隱藏項目狀態

錯誤 無法解析相依性 'SixLabors.Fonts'。已使用來源: 'nuget.org', 'Microsoft Visual Studio Offline Packages'。

勾選「包括搶鮮版」,單獨先安裝 SixLabors.Fonts

WebApplication1

正在安裝:

System.Buffers.4.5.1

System.IO.Compression.4.3.0

System.IO.FileSystem.Primitives.4.3.0

System.IO.UnmanagedMemoryStream.4.3.0

System.Numerics.Vectors.4.5.0

System.Runtime.CompilerServices.Unsafe.4.7.0

System.Memory.4.5.4

System.Threading.Tasks.Parallel.4.3.0

System.ValueTuple.4.5.0

SixLabors.Fonts.1.0.0-beta19

取消勾選「包括搶鮮版」,安裝 ClosedXML

WebApplication1

正在安裝:

DocumentFormat.OpenXml.2.16.0

ExcelNumberFormat.1.1.0

Irony.NetCore.1.0.11

System.IO.Packaging.6.0.0

XLParser.1.5.2

ClosedXML.0.101.0


點「更新」頁籤,勾選「選取所有封裝」,按下「更新」按鈕

WebApplication1

更新:

ClosedXML.0.97.0 -> ClosedXML.0.101.0

XLParser.1.5.2 -> XLParser.1.6.3

System.Memory.4.5.4 -> System.Memory.4.5.5

System.Runtime.CompilerServices.Unsafe.4.7.0 -> System.Runtime.CompilerServices.Unsafe.7.0.0-preview.2.22152.2

System.IO.Packaging.4.7.0 -> System.IO.Packaging.8.0.0-preview.3.23174.8

Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1 -> Microsoft.CodeDom.Providers.DotNetCompilerPlatform.4.1.0

Irony.NetCore.1.0.11 -> Irony.NetCore.1.1.11

DocumentFormat.OpenXml.2.16.0 -> DocumentFormat.OpenXml.2.20.0

正在安裝:

System.Reflection.Emit.ILGeneration.4.3.0

System.Reflection.Emit.Lightweight.4.3.0


點「更新」頁籤,勾選「選取所有封裝」,按下「更新」按鈕

WebApplication1

更新:

System.Reflection.Emit.Lightweight.4.3.0 -> System.Reflection.Emit.Lightweight.4.7.0

System.Reflection.Emit.ILGeneration.4.3.0 -> System.Reflection.Emit.ILGeneration.4.7.0

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

也就是還是會用到。

(完)

相關

[研究]ASP.NET WebForm,ClosedXML 匯出 .xlsx 出錯:無法載入檔案或組件 'Irony

[研究]ASP.NET WebForm,安裝 ClosedXML 0.101.0相依套件測試

[研究]ASP.NET WebForm,安裝 ClosedXML 0.97 相依套件測試