C#_.net core 3.0自定義讀取.csv文件數據_解決首行不是標題的問題_Linqtocsv改進

来源:https://www.cnblogs.com/lxhbky/archive/2020/01/20/12219080.html
-Advertisement-
Play Games

linqtocsv文件有不太好的地方就是:無法設置標題的行數,預設首行就是標題,這不是很尷尬嗎? 並不是所有的csv文件嚴格寫的首行是標題,下麵全是數據,我接受的任務就是讀取很多.csv報表數據,裡面就有很多前幾行是說明性內容,下麵才是標題和數據。為了更好的解決這個問題,自己寫吧... 本博客沒有照 ...


  linqtocsv文件有不太好的地方就是:無法設置標題的行數,預設首行就是標題,這不是很尷尬嗎?   並不是所有的csv文件嚴格寫的首行是標題,下麵全是數據,我接受的任務就是讀取很多.csv報表數據,裡面就有很多前幾行是說明性內容,下麵才是標題和數據。為了更好的解決這個問題,自己寫吧...

  本博客沒有照搬linqtocsv全部源碼,保留了主要功能,並對其優化,為我所用,哈哈...

  

  下麵是主要代碼:

  1-主文件CsvHelper:

  這裡在獨自解析數據的時候,遇到了很多坑:

  a-遇到數據含有分隔符的問題的解決辦法,代碼已經包含了

  b-遇到瞭解析源文檔數據時,未指定字元編碼時,部分數據丟失導致csv文件個別行數據解析異常的問題,針對該問題,就是老老實實把讀取文件時加了字元編碼的參數進去,預設UTF-8。  

 

using Microsoft.Extensions.Logging;
using PaymentAccountAPI.Helper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace PaymentAccountAPI.CSV
{
    public class CsvHelper
    {
        /// <summary>
        /// 日誌
        /// </summary>
        private ILogger _Logger { get; set; }

        public CsvHelper(ILogger<CsvHelper> logger)
        {
            this._Logger = logger;
        }

        public List<T> Read<T>(string filePath, CsvFileDescription fileDescription) where T : class, new()
        {
            List<T> tList = new List<T>(50 * 10000);

            T t = null;
            int currentRawIndex = 1;

            if (File.Exists(filePath))
            {
                using (StreamReader streamReader = new StreamReader(filePath, fileDescription.Encoding))
                {
                    Dictionary<int, FieldMapper> fieldMapperDic = FieldMapper.GetModelFieldMapper<T>().ToDictionary(m => m.CSVTitleIndex);
                    string rawValue = null;
                    string[] rawValueArray = null;
                    PropertyInfo propertyInfo = null;
                    string propertyValue = null;
                    bool rawReadEnd = false;

                    bool isExistSplitChart = false;
                    do
                    {
                        rawValue = streamReader.ReadLine();

                        //標題行
                        if (currentRawIndex > fileDescription.TitleRawIndex)
                        {
                            if (!string.IsNullOrEmpty(rawValue))
                            {
                                //替換字元串含有分隔符為{分隔符},最後再替換回來
                                if (rawValue.Contains("\""))
                                {
                                    isExistSplitChart = true;

                                    int yhBeginIndex = 0;
                                    int yhEndIndex = 0;
                                    string yhText = null;
                                    do
                                    {
                                        yhBeginIndex = StringHelper.GetIndexOfStr(rawValue, "\"", 1);
                                        yhEndIndex = StringHelper.GetIndexOfStr(rawValue, "\"", 2);
                                        yhText = rawValue.Substring(yhBeginIndex, (yhEndIndex - yhBeginIndex + 1));
                                        string newYHText = yhText.Replace("\"", "").Replace(fileDescription.SeparatorChar.ToString(), "{分隔符}");
                                        rawValue = rawValue.Replace(yhText, newYHText);
                                    } while (rawValue.Contains("\""));
                                }

                                rawValueArray = rawValue.Split(fileDescription.SeparatorChar);

                                t = new T();
                                foreach (var fieldMapper in fieldMapperDic)
                                {
                                    propertyInfo = fieldMapper.Value.PropertyInfo;
                                    propertyValue = rawValueArray[fieldMapper.Key - 1];
                                    if (!string.IsNullOrEmpty(propertyValue))
                                    {
                                        try
                                        {
                                            if (isExistSplitChart && propertyValue.Contains("{分隔符}"))
                                            {
                                                propertyValue = propertyValue.Replace("{分隔符}", fileDescription.SeparatorChar.ToString());
                                            }

                                            TypeHelper.SetPropertyValue(t, propertyInfo.Name, propertyValue);
                                        }
                                        catch (Exception e)
                                        {
                                            this._Logger.LogWarning(e, $"第{currentRawIndex + 1}行數據{propertyValue}轉換屬性{propertyInfo.Name}-{propertyInfo.PropertyType.Name}失敗!");
                                            continue;
                                        }
                                    }
                                }
                                tList.Add(t);
                            }
                            else
                            {
                                rawReadEnd = true;
                            }
                        }
                        currentRawIndex++;
                    } while (rawReadEnd == false);
                }
            }


            return tList;
        }

        public void WriteFile<T>(string path, List<T> tList, CsvFileDescription fileDescription) where T : class, new()
        {
            if (!string.IsNullOrEmpty(path))
            {
                string fileDirectoryPath = null;
                if (path.Contains("\\"))
                {
                    fileDirectoryPath = path.Substring(0, path.LastIndexOf('\\'));
                }
                else
                {
                    fileDirectoryPath = path.Substring(0, path.LastIndexOf('/'));
                }
                if (!Directory.Exists(fileDirectoryPath))
                {
                    Directory.CreateDirectory(fileDirectoryPath);
                }

                int dataCount = tList.Count;
                Dictionary<int, FieldMapper> fieldMapperDic = FieldMapper.GetModelFieldMapper<T>().ToDictionary(m => m.CSVTitleIndex);
                int titleCount = fieldMapperDic.Keys.Max();
                string[] rawValueArray = new string[titleCount];
                StringBuilder rawValueBuilder = new StringBuilder();
                string rawValue = null;
                T t = null;
                PropertyInfo propertyInfo = null;
                int currentRawIndex = 1;
                int tIndex = 0;

                using (StreamWriter streamWriter = new StreamWriter(path, false, fileDescription.Encoding))
                {
                    do
                    {
                        try
                        {
                            rawValue = "";

#if DEBUG
                            if (currentRawIndex % 10000 == 0)
                            {
                                this._Logger.LogInformation($"已寫入文件:{path},數據量:{currentRawIndex}");
                            }
#endif

                            if (currentRawIndex >= fileDescription.TitleRawIndex)
                            {
                                //清空數組數據
                                for (int i = 0; i < titleCount; i++)
                                {
                                    rawValueArray[i] = "";
                                }

                                if (currentRawIndex > fileDescription.TitleRawIndex)
                                {
                                    t = tList[tIndex];
                                    tIndex++;
                                }
                                foreach (var fieldMapperItem in fieldMapperDic)
                                {
                                    //寫入標題行
                                    if (currentRawIndex == fileDescription.TitleRawIndex)
                                    {
                                        rawValueArray[fieldMapperItem.Key - 1] = fieldMapperItem.Value.CSVTitle;
                                    }
                                    //真正的數據從標題行下一行開始寫
                                    else
                                    {
                                        propertyInfo = fieldMapperItem.Value.PropertyInfo;
                                        object propertyValue = propertyInfo.GetValue(t);
                                        string formatValue = null;
                                        if (propertyValue != null)
                                        {
                                            if (propertyInfo.PropertyType is IFormattable && !string.IsNullOrEmpty(fieldMapperItem.Value.OutputFormat))
                                            {
                                                formatValue = ((IFormattable)propertyValue).ToString(fieldMapperItem.Value.OutputFormat, null);
                                            }
                                            else
                                            {
                                                formatValue = propertyValue.ToString();
                                            }

                                            //如果屬性值含有分隔符,則使用雙引號包裹
                                            if (formatValue.Contains(fileDescription.SeparatorChar.ToString()))
                                            {
                                                formatValue = $"\"{formatValue}\"";
                                            }
                                            rawValueArray[fieldMapperItem.Key - 1] = formatValue;
                                        }
                                    }
                                }
                                rawValue = string.Join(fileDescription.SeparatorChar, rawValueArray);
                            }
                            rawValueBuilder.Append(rawValue + "\r\n");
                        }
                        catch (Exception e)
                        {
                            this._Logger.LogWarning(e, $"(異常)Excel第{currentRawIndex}行,數據列表第{tIndex + 1}個數據寫入失敗!rawValue:{rawValue}");
                            throw;
                        }

                        currentRawIndex++;
                    } while (tIndex < dataCount);
                    streamWriter.Write(rawValueBuilder.ToString());

                    streamWriter.Close();
                    streamWriter.Dispose();
                }
            }
        }

    }
}

 

  2-CSV映射類特性:

  

using System;

namespace PaymentAccountAPI.CSV
{
    /// <summary>
    /// Csv文件類特性標記
    /// </summary>
    [System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple = false)]
    public class CsvColumnAttribute : System.Attribute
    {
        internal const int defaultTitleIndex = Int32.MaxValue;
        /// <summary>
        /// 標題
        /// </summary>
        public string Title { get; set; }
        /// <summary>
        /// 標題位置(從1開始)
        /// </summary>
        public int TitleIndex { get; set; }
        /// <summary>
        /// 字元輸出格式(數字和日期類型需要)
        /// </summary>
        public string OutputFormat { get; set; }

        public CsvColumnAttribute()
        {
            Title = "";
            TitleIndex = defaultTitleIndex;
            OutputFormat = "";
        }

        public CsvColumnAttribute(string title, int titleIndex, string outputFormat)
        {
            Title = title;
            TitleIndex = titleIndex;
            OutputFormat = outputFormat;
        }
    }
}

 

  3-CSV文件描述信息類:

  

using System.Text;

namespace PaymentAccountAPI.CSV
{
    public class CsvFileDescription
    {
        public CsvFileDescription() : this(1)
        {
        }
        public CsvFileDescription(int titleRawIndex) : this(',', titleRawIndex, Encoding.UTF8)
        {
        }
        public CsvFileDescription(char separatorChar, int titleRawIndex, Encoding encoding)
        {
            this.SeparatorChar = separatorChar;
            this.TitleRawIndex = titleRawIndex;
            this.Encoding = encoding;
        }

        /// <summary>
        /// CSV文件字元編碼
        /// </summary>
        public Encoding Encoding { get; set; }

        /// <summary>
        /// 分隔符(預設為(,),也可以是其他分隔符如(\t))
        /// </summary>
        public char SeparatorChar { get; set; }
        /// <summary>
        /// 標題所在行位置(預設為1,沒有標題填0)
        /// </summary>
        public int TitleRawIndex { get; set; }

    }
}

 

  4-映射類獲取關係幫助類:

  

using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace PaymentAccountAPI.CSV
{
    /// <summary>
    /// 欄位映射類
    /// </summary>
    public class FieldMapper
    {
        /// <summary>
        /// 屬性信息
        /// </summary>
        public PropertyInfo PropertyInfo { get; set; }
        /// <summary>
        /// 標題
        /// </summary>
        public string CSVTitle { get; set; }
        /// <summary>
        /// 標題下標位置
        /// </summary>
        public int CSVTitleIndex { get; set; }
        /// <summary>
        /// 字元輸出格式(數字和日期類型需要)
        /// </summary>
        public string OutputFormat { get; set; }

        public static List<FieldMapper> GetModelFieldMapper<T>()
        {
            List<FieldMapper> fieldMapperList = new List<FieldMapper>(100);

            List<PropertyInfo> tPropertyInfoList = typeof(T).GetProperties().ToList();
            CsvColumnAttribute csvColumnAttribute = null;
            foreach (var tPropertyInfo in tPropertyInfoList)
            {
                csvColumnAttribute = (CsvColumnAttribute)tPropertyInfo.GetCustomAttribute(typeof(CsvColumnAttribute));
                if (csvColumnAttribute != null)
                {
                    fieldMapperList.Add(new FieldMapper
                    {
                        PropertyInfo = tPropertyInfo,
                        CSVTitle = csvColumnAttribute.Title,
                        CSVTitleIndex = csvColumnAttribute.TitleIndex,
                        OutputFormat = csvColumnAttribute.OutputFormat
                    });
                }
            }
            return fieldMapperList;
        }

    }

}

 

  5-其他擴展類:

  

namespace PaymentAccountAPI.Helper
{
    public class StringHelper
    {
        /// <summary>
        /// 獲取字元串中第strPosition個位置的str的下標
        /// </summary>
        /// <param name="text"></param>
        /// <param name="str"></param>
        /// <param name="strPosition"></param>
        /// <returns></returns>
        public static int GetIndexOfStr(string text, string str, int strPosition)
        {
            int strIndex = -1;

            int currentPosition = 0;
            if (!string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(str) && strPosition >= 1)
            {
                do
                {
                    currentPosition++;
                    if (strIndex == -1)
                    {
                        strIndex = text.IndexOf(str);
                    }
                    else
                    {
                        strIndex = text.IndexOf(str, strIndex + 1);
                    }
                } while (currentPosition < strPosition);
            }

            return strIndex;
        }
    }
}

 

 

  最後就是將CsvHelper註入到單例中,就可以使用了...


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 基本構架 所有的C程式都有一個 main 函數.其後包含在大括弧中的是 main 函數的內容. main函數是程式的入口,程式運行後,先進入 main 函數,然後一次執行 main 函數體中的語句. 這是一個例子: 簡單來說,寫在 main 中的內容會在程式啟動時執行.main 函數中的內容是程式的 ...
  • 功能描述:做的是物聯網的項目,Excel導入實現的功能是將Excel中的數據批量的導入AEP系統,再導入我們系統中。目前已經完成該功能,前端還會添加進度條優化。Excel模板: 前端向後端傳遞的參數: 前端代碼: <Upload name="wlwDeviceFile" ref="upload" : ...
  • 導入下列依賴包,搞定 sudo apt-get install python3 python-dev python3-dev build-essential libssl-dev libffi-dev libxml2-dev libxslt1-dev zlib1g-dev python-pip 上訴 ...
  • 引言 昨日接了一個阿裡外包的電話面試,問了一些技術問題感覺到自己是真的菜,接觸Java開發已經也有一段時間,技術方面說來慚愧,一直以來只是局限於框架工具的用法,也沒有進行瞭解其實現的原理,更重要的是一直沒有歸納和總結,這次把這些問題記錄下來,相關的知識點也找了一些資料學習下。 問題 1. Count ...
  • 錯誤信息 錯誤原因 so文件損壞 或者ida換成32 解決辦法 重新獲得so文件,或者調整ida的位數 ...
  • 在JAVA中集合是一種比較基礎重要的數據結構,對集合的常用操作,不同集合直接的比較是非常重要的,這裡ConcurrentHashMap是一個線程安全並且效率非常高的集合,主要講解這裡如何去使用這個集合,和集合的效率比較 ...
  • 首先需要pip3 install wakeonlan 然後在電腦需要你的網卡支持網路喚醒電腦。 然後在主板BIOS開啟支持喚醒。 在系統網卡屬性里選上“允許電腦關閉此設備以節約電源”,“允許此設備喚醒電腦” 然後以下就是python代碼,非常簡單。from wakeonlan import s ...
  • 本篇博客園是被任務所逼,而已有的使用nopi技術的文檔技術經驗又不支持我需要的應對各種複雜需求的苛刻要求,只能自己造輪子封裝了,由於需要應對很多總類型的數據採集需求,因此有了本篇博客的代碼封裝,下麵一點點介紹吧: 收集excel你有沒有遇到過一下痛點: 1-需要收集指定行標題位置的數據,我的標題行不 ...
一周排行
    -Advertisement-
    Play Games
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 本章將和大家分享ES的數據同步方案和ES集群相關知識。廢話不多說,下麵我們直接進入主題。 一、ES數據同步 1、數據同步問題 Elasticsearch中的酒店數據來自於mysql資料庫,因此mysql數據發生改變時,Elasticsearch也必須跟著改變,這個就是Elasticsearch與my ...
  • 引言 在我們之前的文章中介紹過使用Bogus生成模擬測試數據,今天來講解一下功能更加強大自動生成測試數據的工具的庫"AutoFixture"。 什麼是AutoFixture? AutoFixture 是一個針對 .NET 的開源庫,旨在最大程度地減少單元測試中的“安排(Arrange)”階段,以提高 ...
  • 經過前面幾個部分學習,相信學過的同學已經能夠掌握 .NET Emit 這種中間語言,並能使得它來編寫一些應用,以提高程式的性能。隨著 IL 指令篇的結束,本系列也已經接近尾聲,在這接近結束的最後,會提供幾個可供直接使用的示例,以供大伙分析或使用在項目中。 ...
  • 當從不同來源導入Excel數據時,可能存在重覆的記錄。為了確保數據的準確性,通常需要刪除這些重覆的行。手動查找並刪除可能會非常耗費時間,而通過編程腳本則可以實現在短時間內處理大量數據。本文將提供一個使用C# 快速查找並刪除Excel重覆項的免費解決方案。 以下是實現步驟: 1. 首先安裝免費.NET ...
  • C++ 異常處理 C++ 異常處理機制允許程式在運行時處理錯誤或意外情況。它提供了捕獲和處理錯誤的一種結構化方式,使程式更加健壯和可靠。 異常處理的基本概念: 異常: 程式在運行時發生的錯誤或意外情況。 拋出異常: 使用 throw 關鍵字將異常傳遞給調用堆棧。 捕獲異常: 使用 try-catch ...
  • 優秀且經驗豐富的Java開發人員的特征之一是對API的廣泛瞭解,包括JDK和第三方庫。 我花了很多時間來學習API,尤其是在閱讀了Effective Java 3rd Edition之後 ,Joshua Bloch建議在Java 3rd Edition中使用現有的API進行開發,而不是為常見的東西編 ...
  • 框架 · 使用laravel框架,原因:tp的框架路由和orm沒有laravel好用 · 使用強制路由,方便介面多時,分多版本,分文件夾等操作 介面 · 介面開發註意欄位類型,欄位是int,查詢成功失敗都要返回int(對接java等強類型語言方便) · 查詢介面用GET、其他用POST 代碼 · 所 ...
  • 正文 下午找企業的人去鎮上做貸後。 車上聽同事跟那個司機對罵,火星子都快出來了。司機跟那同事更熟一些,連我在內一共就三個人,同事那一手指桑罵槐給我都聽愣了。司機也是老社會人了,馬上聽出來了,為那個無辜的企業經辦人辯護,實際上是為自己辯護。 “這個事情你不能怪企業。”“但他們總不能讓銀行的人全權負責, ...
  • 1. JUnit 最佳實踐指南 原文: https://howtodoinjava.com/best-practices/unit-testing-best-practices-junit-reference-guide/ 我假設您瞭解 JUnit 的基礎知識。 如果您沒有基礎知識,請首先閱讀(已針 ...