.net core 讀取Excal文件數據及注意事項


添加ExcelDataReader.DataSet引用。

調用下列方法:

    public class XlsHelper
    {
        public static System.Data.DataSet GetXlsToDataSet(string filePath)
        {
            using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
            {
                // Auto-detect format, supports:
                //  - Binary Excel files (2.0-2003 format; *.xls)
                //  - OpenXml Excel files (2007 format; *.xlsx)
                using (var reader = ExcelReaderFactory.CreateReader(stream))
                {
                    // Choose one of either 1 or 2:

                    // 1. Use the reader methods
                    do
                    {
                        while (reader.Read())
                        {
                            // reader.GetDouble(0);
                        }
                    } while (reader.NextResult());

                    // 2. Use the AsDataSet extension method
                    var result = reader.AsDataSet();
                    return result;
                    // The result of each spreadsheet is in result.Tables
                }
            }
        }
    }

默認情況下,ExcelDataReader引發NotSupportedException“沒有數據可用於編碼1252。” 在.NET Core上。

要解決此問題,請在程序包中添加一個依賴項System.Text.Encoding.CodePages,然后添加代碼以在應用程序初始化期間注冊代碼頁提供程序(f.ex in Startup.cs):

System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

  

這是解析使用DOS時代代碼頁編碼的BIFF2-5二進制Excel文檔中的字符串所必需的。這些編碼默認情況下在完整的.NET Framework中注冊,但不在.NET Core上注冊。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM