溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時間:2021-11-24 13:54:05 來源:億速云 閱讀:109 作者:柒染 欄目:編程語言

本篇文章為大家展示了如何用ADO.NET實現(xiàn)txt與Excel的互相轉(zhuǎn)換,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。

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

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

EXECL轉(zhuǎn)換TXT:

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

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

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

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

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

/// <summary> /// 生成txt  /// </summary> /// <param name="sender"></param> /// <param name="e"></param> privatevoidbtnGenerate_Click(objectsender, EventArgs e){if(txtExcelPath.Text.Trim() == ""){MessageBox.Show("請導(dǎo)入excel");return;}if(cboSheet.Text.Trim() == ""){MessageBox.Show("沒有存在的excel頁");  return;}stringcolName = "";stringrowText = "";  StringBuilder strbui = newStringBuilder();   try{DataTable dt = GetExcelData.ExcelObj.GetExcelDB(txtExcelPath.Text.Trim(), cboSheet.Text.Trim());  for(inti = 0; i <dt.Columns.Count; i++){stringtempName = dt.Columns[i].ColumnName.Trim();  byte[] byte_len = Encoding.Default.GetBytes(tempName);if(byte_len.Length <30){intk = 30 - byte_len.Length;for(intt = k; t >0; t--){tempName += " ";}}  else{byte[] CutStr_Bytes1 = newbyte[30];  Array.Copy(byte_len, 0, CutStr_Bytes1, 0, 30);  tempName = myEncoding.GetString(CutStr_Bytes1);}colName += tempName; }  for(inti = 0; i <dt.Rows.Count; i++){for(intj = 0; j <dt.Columns.Count; j++){stringtempName = dt.Rows[i][j].ToString();byte[] byte_len = Encoding.Default.GetBytes(tempName);if(byte_len.Length <30){intk = 30 - byte_len.Length;for(intt = k; t >0; t--){tempName += " ";}}else{byte[] CutStr_Bytes1 = newbyte[30];Array.Copy(byte_len, 0, CutStr_Bytes1, 0, 30);tempName = myEncoding.GetString(CutStr_Bytes1);} strbui.Append(tempName);}strbui.Append(" ");}rowText = strbui.ToString(); }  catch(Exception ex){MessageBox.Show(ex.Message);}try{SaveFileDialog saveFileDialog = newSaveFileDialog();  saveFileDialog.Filter = "文本文件|*.txt";  if(saveFileDialog.ShowDialog() == DialogResult.OK){StreamWriter streamWriter = newStreamWriter(saveFileDialog.FileName, false, System.Text.Encoding.GetEncoding("gb2312"));  streamWriter.Write(colName + " "+ rowText);streamWriter.Close();}}  catch(Exception ex){MessageBox.Show("保存txt失敗"+ ex.Message);  }}

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

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

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

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

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

上述內(nèi)容就是如何用ADO.NET實現(xiàn)txt與Excel的互相轉(zhuǎn)換,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI