C#的CSV檔案匯入匯出

來源:互聯網
上載者:User

1. asp.net的匯出:

<pre name="code" class="csharp">StringBuilder DATA = new StringBuilder("");Response.Clear();Response.ContentType = "text/plain; charset=Shift_JIS";Response.AddHeader("content-disposition", "attachment; filename=" + filename + ".csv");...  //從DB中取得DataDATA.Append(...);//將Data寫入DATA,CSV檔案要以”,"分割Response.Write(DATA.ToString());Response.End();

2.WinForm的匯出:
... //取得儲存路徑... //從DB中取得Data... //同1,將以","分割的資料寫入StringBuilderStreamWriter sw = new StreamWriter(exportPath, false, Encoding.GetEncoding("shift_jis"));sw.Write(stringData.ToString());

3.asp.net的匯入:
 
HtmlInputFile txtHtmlInputFile = txtFile; //txtFile是畫面中的input控制項中取得的檔案System.IO.Stream inStream = txtHtmlInputFile.PostedFile.InputStream;//DataStream讀取Byte[] mstreamBackUp = new Byte[inStream.Length];inStream.Read(mstreamBackUp, 0, int.Parse(inStream.Length.ToString()));//用來Check的StreamMemoryStream chkStream = new MemoryStream(mstreamBackUp);System.Text.Encoding enc = System.Text.Encoding.Default;TextFieldParser parser = new TextFieldParser(chkStream, enc);parser.TextFieldType = FieldType.Delimited;parser.SetDelimitens(",");parser.TrimWhiteSpace = false;while(!parser.EndOfData){String strOrgText = parser.ReadFields();//讀取一行String[] strAryText = new String[strOrgText.Length];int i=0;foreach(String field in strOrgText){strArgText[i] = field;i++;}...//執行各種Check...//向DB插入資料}parser.Close();parser = null;

4.WinForm的匯入:
Private sctTeam[] ImpTeamAry;//儲存用的匯入資料Private struct sctTeam{public String itemA;...//B...//C}//ImpTeamAry中寫入CSV資料//用OpenFileDialog取得CSV檔案String strFileName = openFileDialog1.FileName;StreamReader sr = new StreamReader(strFileName, System.Text.EncodingDefault);String strText = sr.ReadToEnd();//讀到最後If (strText.Length <= 0 || strText.SubString(0, 1) ! "\""){...//讀取失敗資訊}sr.Close();strText.Replace("\r", "");//刪除換行String[] strTextAry = strText.Split('\n');if (strTextAry.Length < 1){...//讀取失敗資訊}//定義和memoryImpTeamAry = new sctTeam[strTextAry.Length];for(int i=0; i<strTextAry.Length; i++){ImpTeamAry[i] = new sctTeam();//確保Memory}//取得資料int j=0;//資料數組Indexfor (int ii=0; ii<=strTextAry.Length-1; ii++){if(strTextAry[ii].ToString().Trim().Length == 0)continue;//各項目取得String[] strAryField = strTextAry[ii].Split(',');ImpTeamAry[j].itemA = strAryField[0].ToString().Replace("\"", "");...//B...//Cj++;}


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.