DataTable 轉成 CSV 檔函式程式碼如下:
public void CreateCSVFile(DataTable dt, string strFilePath) // strFilePath 為輸出檔案路徑 (含檔名)讀取 CSV 轉成 DataTable 函式程式碼如下:
{
StreamWriter sw = new StreamWriter(strFilePath, false);
int intColCount = dt.Columns.Count;
if (dt.Columns.Count > 0)
sw.Write(dt.Columns[0]);
for (int i = 1; i < dt.Columns.Count; i++)
sw.Write("," + dt.Columns[i]);
sw.Write(sw.NewLine);
foreach (DataRow dr in dt.Rows)
{
if (dt.Columns.Count > 0 && !Convert.IsDBNull(dr[0]))
sw.Write(Encode(Convert.ToString(dr[0])));
for (int i = 1; i < intColCount; i++)
sw.Write("," + Encode(Convert.ToString(dr[i])));
sw.Write(sw.NewLine);
}
sw.Close();
}
public string Encode(string strEnc)
{
return System.Web.HttpUtility.UrlEncode(strEnc);
}
public DataTable ReadCSVFile(string strFilePath, string strFileName) // strFilePath 為檔案所在資料夾,strFileName 為檔案名稱
{
OleDbConnection connection = new OleDbConnection(string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}; Extended Properties=""text;HDR=Yes;FMT=Delimited"";", strFilePath));
OleDbCommand command = new OleDbCommand("SELECT * FROM " + strFileName, connection);
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
adapter.Fill(dt);
return dt;
}
回目錄
回首頁
沒有留言 :
張貼留言