自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

用ADO.NET實(shí)現(xiàn)txt與Excel的互相轉(zhuǎn)換

開發(fā) 后端
將TXT文檔與Excel之間進(jìn)行相互轉(zhuǎn)換可以幫助大家在開發(fā)上有很大作用。txt文本是沒有格式的,但是excel文檔是有格式的,將沒有格式的東西轉(zhuǎn)換為有格式的東西,可以方便別人閱讀。

  在園子里看過很多文章,關(guān)于設(shè)計(jì)模式,關(guān)于架構(gòu)等等,我在這里談?wù)勔恍┸浖墓δ?,為什么需要這樣的功能。

  我前段時(shí)間寫了一個(gè)TXT與EXCEL為什么要互相轉(zhuǎn)換的功能,可能有人會問,這樣的功能有什么作用?是的,這小功能在軟件開發(fā)上有很大的作用的。txt文本是沒有格式的,但是excel文檔是有格式的,將沒有格式的東西轉(zhuǎn)換為有格式的東西,可以方便別人閱讀,除此之外,很多軟件的服務(wù)端傳給客戶端的東西是沒有格式的東西,就是一個(gè)字符串,客戶端接收到這個(gè)字符串,如何格式化,變成我們需要的東西,比如說excel文檔。反之,有個(gè)excel文檔,也要將它變成字符串才能順利地發(fā)給服務(wù)端,或者發(fā)給調(diào)用者。當(dāng)然,可能有人會說傳字符串的方式非常落后,現(xiàn)在都有webservice這個(gè)標(biāo)準(zhǔn)化的東西,webservice是有格式的,而且很好傳輸與解析,但是如果你后臺是用C語言寫,或者是更低級語言編寫的,并沒有類似于webservice的東西,那就只能傳輸字符流了。其實(shí)webservice傳輸?shù)囊彩莣sdl的文本,它本身也是一堆字符而已,只不過是通過一些組件變成我們需要的東西,例如類。webservice只是一個(gè)通用的標(biāo)準(zhǔn),也可以制定屬于自己的標(biāo)準(zhǔn)。

  EXECL轉(zhuǎn)換TXT:

  首先,需要讀取EXCEL文檔,讀取excel文檔可以通過ADO.NET的Connection。

  1.   /// <summary>/// 獲取excel  
  2. /// </summary>///   
  3. <param name="excelPath"></param>///  
  4.  <returns></returns> 
  5. privateOleDbConnection getCon(stringexcelPath){
  6. try{stringstrConn = "Provider=Microsoft.Jet.OLEDB.4.0;"
  7. "Data Source="+ excelPath + ";"+ "Extended Properties=Excel 8.0;";  
  8. OleDbConnection conn = newOleDbConnection(strConn);conn.Open();returnconn;}
  9. catch(Exception ex){
  10. thrownewArgumentException("打開excel失敗", ex.Message);}} 

  然后,需要讀取excel文檔的每一頁,與讀取excel的內(nèi)容

  1. /// <summary>/// 獲取excel頁  
  2. /// </summary>///   
  3. <param name="excelPath"></param> 
  4. /// <returns></returns>publicstring[]   
  5. getSheets(stringexcelPath){OleDbConnection conn = getCon(excelPath);
  6. try{DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, newobject[] {   
  7. null, null, null, "Table"});  
  8. string[] strTableNames = newstring[dtSheetName.Rows.Count];  
  9. inti = 0;for(intk = 0; k <dtSheetName.Rows.Count; k++){  
  10. //把有下劃線的excel頁去掉
  11. if(!dtSheetName.Rows[k]["TABLE_NAME"].ToString().Contains("_")){strTableNames[i] = dtSheetName.Rows[k]["TABLE_NAME"].ToString();i++;}}
  12. returnstrTableNames;} catch(Exception ex){ throwex; }finally{ conn.Close(); }}   
  13. /// <summary>/// 獲取excel的數(shù)據(jù)  
  14. /// </summary>///   
  15. <param name="excelPath"></param>/// 
  16. <param name="sheetName"></param>/// 
  17. <returns></returns>publicDataTable GetExcelDB(stringexcelPath,stringsheetName){OleDbConnection conn = getCon(excelPath);
  18. try{DataTable dt = newDataTable();OleDbDataAdapter myada = null;
  19. stringstrExcel = "select * from ["+ sheetName + "]";myada = newOleDbDataAdapter(strExcel, conn);
  20. myada.Fill(dt);returndt;}catch(Exception ex){ throwex; }finally{ conn.Close(); }} 

  ***,生成TXT文本,因?yàn)閠xt文本是沒有格式的,因此我們需要制定一些標(biāo)準(zhǔn),我設(shè)定每個(gè)單元格的長度都為30個(gè)字節(jié),excel的每一行對應(yīng)txt的一行。如果單元格的長度是不一樣的,可以制定一個(gè)list。有了標(biāo)準(zhǔn),這樣在txt轉(zhuǎn)excel是才能成功。這里需要注意一點(diǎn),中文字符與英文字符的節(jié)長度是不一樣的,中文占兩個(gè)字節(jié),而英文是占1個(gè)字節(jié),因此在轉(zhuǎn)換的時(shí)候需要多做一些工作。

  

  1. /// <summary> 
  2. /// 生成txt  
  3. /// </summary> 
  4. /// <param name="sender"></param> 
  5. /// <param name="e"></param> 
  6. privatevoidbtnGenerate_Click(objectsender, EventArgs e){
  7. if(txtExcelPath.Text.Trim() == ""){MessageBox.Show("請導(dǎo)入excel");
  8. return;}
  9. if(cboSheet.Text.Trim() == ""){MessageBox.Show("沒有存在的excel頁");  
  10. return;}stringcolName = "";stringrowText = "";  
  11. StringBuilder strbui = newStringBuilder();   
  12. try{DataTable dt = GetExcelData.ExcelObj.GetExcelDB(txtExcelPath.Text.Trim(), cboSheet.Text.Trim());  
  13. for(inti = 0; i <dt.Columns.Count; i++){stringtempName = dt.Columns[i].ColumnName.Trim();  
  14. byte[] byte_len = Encoding.Default.GetBytes(tempName);
  15. if(byte_len.Length <30){intk = 30 - byte_len.Length;for(intt = k; t >0; t--){tempName += " ";}}  
  16. else{byte[] CutStr_Bytes1 = newbyte[30];  
  17. Array.Copy(byte_len, 0, CutStr_Bytes1, 0, 30);  
  18. tempName = myEncoding.GetString(CutStr_Bytes1);}colName += tempName; }  
  19. for(inti = 0; i <dt.Rows.Count; i++){
  20. for(intj = 0; j <dt.Columns.Count; j++){
  21. stringtempName = dt.Rows[i][j].ToString();byte[] byte_len = Encoding.Default.GetBytes(tempName);
  22. if(byte_len.Length <30){intk = 30 - byte_len.Length;for(intt = k; t >0; t--){tempName += " ";}}
  23. else{byte[] CutStr_Bytes1 = newbyte[30];
  24. Array.Copy(byte_len, 0, CutStr_Bytes1, 0, 30);
  25. tempName = myEncoding.GetString(CutStr_Bytes1);} 
  26. strbui.Append(tempName);}strbui.Append(" ");}rowText = strbui.ToString(); }  
  27. catch(Exception ex){MessageBox.Show(ex.Message);}
  28. try{SaveFileDialog saveFileDialog = newSaveFileDialog();  
  29. saveFileDialog.Filter = "文本文件|*.txt";  
  30. if(saveFileDialog.ShowDialog() == DialogResult.OK){
  31. StreamWriter streamWriter = newStreamWriter(saveFileDialog.FileName, false, System.Text.Encoding.GetEncoding("gb2312"));  
  32. streamWriter.Write(colName + " "+ rowText);streamWriter.Close();}}  
  33. catch(Exception ex){MessageBox.Show("保存txt失敗"+ ex.Message);  
  34. }}  

   TXT轉(zhuǎn)換EXECL:在txt轉(zhuǎn)換excel的過程中,首先需要獲取txt文本

  1.  /// <summary>///   
  2. /// </summary>StreamReader reader = null;  
  3. /// <summary>///   
  4. /// </summary>Encoding myEncoding = Encoding.GetEncoding("GB2312");  
  5. /// <summary> 
  6. /// 導(dǎo)入txt/// </summary> 
  7. /// <param name="sender"></param> 
  8. /// <param name="e"></param>privatevoidbtnImportTxt_Click(objectsender, EventArgs e){  
  9. OpenFileDialog openFileDialog = newOpenFileDialog();  
  10. openFileDialog.InitialDirectory = "D:\";  
  11. openFileDialog.Filter = "TXT文件|*.txt";  
  12. openFileDialog.RestoreDirectory = true;openFileDialog.FilterIndex = 1;  
  13. if (openFileDialog.ShowDialog() == DialogResult.OK){string fName = openFileDialog.FileName;
  14. textBox2.Text = fName;reader = new StreamReader(fName, System.Text.Encoding.GetEncoding("GB2312")); }}  

 

  然后對文本進(jìn)行處理,用 reader.ReadLine()一行行地往下讀,每讀一行處理一行,直到讀完為止。處理的時(shí)候需要把字符串均等平分,每30個(gè)字節(jié)寫一個(gè)單元格。

  1. /// <summary> 
  2. /// 把字符串均等平分/// </summary> 
  3. /// <param name="SourceString"></param> 
  4. /// <returns></returns>privatestring[] spitText(stringSourceString){intlength = 30;  
  5. intlen = 0;byte[] SourceStr_Bytes = myEncoding.GetBytes(SourceString);  
  6. byte[] CutStr_Bytes1 = newbyte[length];   
  7. if(SourceStr_Bytes.Length % length != 0)len = SourceStr_Bytes.Length / length + 1;  
  8. elselen = SourceStr_Bytes.Length / length;string[] array = newstring[len];inti, j = 0;  
  9. for(i = 0; (i + length) <= SourceStr_Bytes.Length &&SourceStr_Bytes.Length >= i; ){  
  10. Array.Copy(SourceStr_Bytes, i, CutStr_Bytes1, 0, length);array[j] = myEncoding.GetString(CutStr_Bytes1);j++;ii = i + length;}  
  11. if(SourceStr_Bytes.Length % length != 0){
  12. Array.Copy(SourceStr_Bytes, SourceStr_Bytes.Length - i, CutStr_Bytes1, 0, length);array[j] = myEncoding.GetString(CutStr_Bytes1);}returnarray;}   
  13. /// <summary> 
  14. /// 生成txt  
  15. /// </summary> 
  16. /// <param name="sender"></param> 
  17. /// <param name="e"></param>
  18. privatevoidbtnGenTxt_Click(objectsender, EventArgs e){SaveFileDialog saveFileDialog = newSaveFileDialog();saveFileDialog.Filter = "文本文件|*.xls";
  19. if(saveFileDialog.ShowDialog() == DialogResult.OK){StreamWriter sw = newStreamWriter(saveFileDialog.FileName, true, System.Text.Encoding.GetEncoding("GB2312"));stringstr = "";  
  20. if(reader == null){MessageBox.Show("請導(dǎo)入txt");return;}try{  
  21. //寫標(biāo)題stringheadText = reader.ReadLine();  
  22. string[] array = spitText(headText);  
  23. for(inti = 0; i <array.Length; i++){array[i] += " ";str += array[i];}sw.WriteLine(str);  
  24. //寫內(nèi)容stringtext;while((text = reader.ReadLine()) != null){stringtempStr = "";  
  25. string[] arrayText = spitText(text);  
  26. for(intf = 0; f <arrayText.Length; f++){tempStr += arrayText[f] + " ";}sw.WriteLine(tempStr);}sw.Close();}  
  27. catch(Exception ex){MessageBox.Show(ex.Message);}finally{sw.Close();}}}  

 

  好了,到這里,TXT月EXCEL的互相轉(zhuǎn)換功能就做好了,源碼沒找到地方上傳,改天找個(gè)好的網(wǎng)盤上傳。

原文鏈接:http://www.cnblogs.com/suyangbin/archive/2011/11/29/2266938.html

【編輯推薦】

  1. 詳細(xì)述說ADO超時(shí)相關(guān)問題介紹
  2. 漫談ADO.NET連接池相關(guān)注意問題說明
  3. 如何更好的進(jìn)行ADO.NET連接池連接
  4. 剖析ADO.NET連接池優(yōu)缺點(diǎn)
  5. 談?wù)凙DO.NET數(shù)據(jù)庫連接池創(chuàng)建和分配

 

責(zé)任編輯:彭凡 來源: 博客園
相關(guān)推薦

2011-05-20 11:31:07

ADO.NET

2009-12-31 16:09:22

ADO與ADO.NET

2009-11-11 13:59:15

ADO.NET與ADO

2009-11-04 17:03:55

ADO.NET Exc

2009-12-28 15:11:36

ADO.NET專家

2011-06-02 09:39:29

ADO.NET

2009-11-03 16:37:10

2009-12-30 15:11:35

ADO.NET數(shù)據(jù)

2009-11-03 14:22:10

ADO.NET Exc

2009-12-25 15:09:11

ADO.NET選項(xiàng)

2011-03-04 11:08:46

ADO.NET數(shù)據(jù)庫

2009-09-14 13:37:25

LINQ ADO.NE

2009-11-11 10:55:10

ADO.NET對象

2009-12-21 11:00:05

ADO.NET 結(jié)構(gòu)

2009-11-04 14:54:42

ADO.NET與Pow

2011-10-09 13:38:14

數(shù)據(jù)庫

2009-12-21 17:06:41

ADO.NET DbP

2024-06-18 13:17:02

數(shù)據(jù)庫框架

2009-07-06 10:43:51

ADO.NET

2010-01-04 10:48:30

ADO.NET特色
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號