C# CSV文件讀寫

来源:https://www.cnblogs.com/zhengjiabo180609/archive/2018/06/09/9159377.html
-Advertisement-
Play Games

public class CSVFileHelper{ /// <summary> /// 將DataTable中數據寫入到CSV文件中 /// </summary> /// <param name="dt">提供保存數據的DataTable</param> /// <param name="fil ...


public class CSVFileHelper
{
/// <summary>
/// 將DataTable中數據寫入到CSV文件中
/// </summary>
/// <param name="dt">提供保存數據的DataTable</param>
/// <param name="fileName">CSV的文件路徑</param>
public static void SaveCSV(DataTable dt, string fullPath)
{
FileInfo fi = new FileInfo(fullPath);
if (!fi.Directory.Exists)
{
fi.Directory.Create();
}
FileStream fs = new FileStream(fullPath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
//StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
string data = "";
//寫出列名稱
for (int i = 0; i < dt.Columns.Count; i++)
{
data += dt.Columns[i].ColumnName.ToString();
if (i < dt.Columns.Count - 1)
{
data += ",";
}
}
sw.WriteLine(data);
//寫出各行數據
for (int i = 0; i < dt.Rows.Count; i++)
{
data = "";
for (int j = 0; j < dt.Columns.Count; j++)
{
string str = dt.Rows[i][j].ToString();
str = str.Replace("\"", "\"\"");//替換英文冒號 英文冒號需要換成兩個冒號
if (str.Contains(',') || str.Contains('"')
|| str.Contains('\r') || str.Contains('\n')) //含逗號 冒號 換行符的需要放到引號中
{
str = string.Format("\"{0}\"", str);
}

data += str;
if (j < dt.Columns.Count - 1)
{
data += ",";
}
}
sw.WriteLine(data);
}
sw.Close();
fs.Close();
DialogResult result = MessageBox.Show("CSV文件保存成功!");
if (result == DialogResult.OK)
{
System.Diagnostics.Process.Start("explorer.exe", Common.PATH_LANG);
}
}

/// <summary>
/// 將CSV文件的數據讀取到DataTable中
/// </summary>
/// <param name="fileName">CSV文件路徑</param>
/// <returns>返回讀取了CSV數據的DataTable</returns>
public static DataTable OpenCSV(string filePath)
{
Encoding encoding = Common.GetType(filePath); //Encoding.ASCII;//
DataTable dt = new DataTable();
FileStream fs = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);

//StreamReader sr = new StreamReader(fs, Encoding.UTF8);
StreamReader sr = new StreamReader(fs, encoding);
//string fileContent = sr.ReadToEnd();
//encoding = sr.CurrentEncoding;
//記錄每次讀取的一行記錄
string strLine = "";
//記錄每行記錄中的各欄位內容
string[] aryLine = null;
string[] tableHead = null;
//標示列數
int columnCount = 0;
//標示是否是讀取的第一行
bool IsFirst = true;
//逐行讀取CSV中的數據
while ((strLine = sr.ReadLine()) != null)
{
//strLine = Common.ConvertStringUTF8(strLine, encoding);
//strLine = Common.ConvertStringUTF8(strLine);

if (IsFirst == true)
{
tableHead = strLine.Split(',');
IsFirst = false;
columnCount = tableHead.Length;
//創建列
for (int i = 0; i < columnCount; i++)
{
DataColumn dc = new DataColumn(tableHead[i]);
dt.Columns.Add(dc);
}
}
else
{
aryLine = strLine.Split(',');
DataRow dr = dt.NewRow();
for (int j = 0; j < columnCount; j++)
{
dr[j] = aryLine[j];
}
dt.Rows.Add(dr);
}
}
if (aryLine != null && aryLine.Length > 0)
{
dt.DefaultView.Sort = tableHead[0] + " " + "asc";
}

sr.Close();
fs.Close();
return dt;
}
}


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

-Advertisement-
Play Games
更多相關文章
  • using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApp1 //函數的遞歸調用 { //F(n)= F(n-1)+F(n-2)... F(1)=... ...
  • 概述 博主自畢業後,進公司就一直是以ASP.NET MVC 5.0 + MySQL 進行項目開發,在項目也使用了很多常用功能,如 WCF、SignalR、微信公眾號API、支付寶API、Dapper等等,前端是大雜燴,如:Bootstrap、AmazeUI、EasyUI、Light7、WeUI等等。 ...
  • 本文所需的一些預備知識可以看這裡: http://www.cnblogs.com/cgzl/p/9010978.html 和 http://www.cnblogs.com/cgzl/p/9019314.html 建立Richardson成熟度2級的POST、GET、PUT、PATCH、DELETE的 ...
  • 一個開發的系統程式從需求、設計到打包、用戶使用的過程中,安全問題一直是開發者關註的焦點。對於用戶來說,不考慮加密工具(如加密精靈等),面對的是一個系統的各個組件集合及各類的配置文件( 如App.Config / Web.Config)。其中,涉及到安全防範問題如App.Config配置文件,裡面會包 ...
  • 發佈好的asp.net core mvc項目, 如果想在window下啟動的話,可以用下麵的命令 dotnet MyProject.dll --urls="https://localhost:7001;http://localhost:7000" --environment=Development ...
  • 大神張善友 分享過一篇 《.NET Core 在騰訊財付通的企業級應用開發實踐》裡面就是用.net core 和 Ocelot搭建的可擴展的高性能Api網關。 Ocelot(http://ocelot.readthedocs.io)是一個用.NET Core實現並且開源的API網關,它功能強大,包括 ...
  • 本利用C# 調用Windows自帶的Windows Media Player 打造一款屬於自己的音樂播放器 ...
  • 1.新建WPF項目; 2.添加引用 .net引用:System.Windows.Forms和WindowsFormsIntegration skyline引用:AxInterop.TerraExplorerX和TerraExplorerX 3.代碼如下: /// <summary> /// Main ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...