用ADO.NET实现txt与Excel的互相转换

在园子里看过很多文章,关于设计模式,关于架构等等,我在这里谈谈一些软件的功能,为什么需要这样的功能。

我前段时间写了一个TXT与EXCEL为什么要互相转换的功能,可能有人会问,这样的功能有什么作用?是的,这小功能在软件开发上有很大的作用的。txt文本是没有格式的,但是excel文档是有格式的,将没有格式的东西转换为有格式的东西,可以方便别人阅读,除此之外,很多软件的服务端传给客户端的东西是没有格式的东西,就是一个字符串,客户端接收到这个字符串,如何格式化,变成我们需要的东西,比如说excel文档。反之,有个excel文档,也要将它变成字符串才能顺利地发给服务端,或者发给调用者。当然,可能有人会说传字符串的方式非常落后,现在都有webservice这个标准化的东西,webservice是有格式的,而且很好传输与解析,但是如果你后台是用C语言写,或者是更低级语言编写的,并没有类似于webservice的东西,那就只能传输字符流了。其实webservice传输的也是wsdl的文本,它本身也是一堆字符而已,只不过是通过一些组件变成我们需要的东西,例如类。webservice只是一个通用的标准,也可以制定属于自己的标准。

EXECL转换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的内容

 
 
  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的数据  
  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文本,因为txt文本是没有格式的,因此我们需要制定一些标准,我设定每个单元格的长度都为30个字节,excel的每一行对应txt的一行。如果单元格的长度是不一样的,可以制定一个list。有了标准,这样在txt转excel是才能成功。这里需要注意一点,中文字符与英文字符的节长度是不一样的,中文占两个字节,而英文是占1个字节,因此在转换的时候需要多做一些工作。

 
 
  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("请导入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转换EXECL:在txt转换excel的过程中,首先需要获取txt文本

 
 
  1.  /// <summary>///   
  2. /// </summary>StreamReader reader = null;  
  3. /// <summary>///   
  4. /// </summary>Encoding myEncoding = Encoding.GetEncoding("GB2312");  
  5. /// <summary> 
  6. /// 导入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")); }}  

然后对文本进行处理,用 reader.ReadLine()一行行地往下读,每读一行处理一行,直到读完为止。处理的时候需要把字符串均等平分,每30个字节写一个单元格。

 
 
  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("请导入txt");return;}try{  
  21. //写标题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. //写内容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的互相转换功能就做好了,源码没找到地方上传,改天找个好的网盘上传。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值