C#操作Excel

作者:追风剑情 发布于:2015-5-5 11:56 分类:C#

一、导出Excel中的所有表到 表名.txt 文件

示例:

项目->添加引用->COM

添加以下引用库

Microsoft Office 14.0 Object Library

Microsoft Excel 14.0 Object Library

Microsoft Word 14.0 Object Library

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6. using System.Reflection;
  7. using Microsoft.Office.Core;
  8. using Microsoft.Office.Interop.Excel;
  9.  
  10. namespace LanguagePack
  11. {
  12. class Program
  13. {
  14. static void Main(string[] args)
  15. {
  16. string excelFileName = "语言包.xlsm";
  17. int keyCol = 1;//语言key所在列号
  18. int langCol = 6;//要导出的语言所在列号
  19.  
  20. if (args.Length > 0)
  21. {
  22. langCol = int.Parse(args[0]);
  23. }
  24. else
  25. {
  26. MENU:
  27. Console.WriteLine("2、简体中文");
  28. Console.WriteLine("3、繁体中文");
  29. Console.WriteLine("4、韩文");
  30. Console.WriteLine("5、越南文");
  31. Console.WriteLine("6、英文");
  32. Console.WriteLine("请选择要导出的语言类型: ");
  33.  
  34. string menu = Console.ReadLine();
  35. if (string.IsNullOrEmpty(menu))
  36. goto MENU;
  37.  
  38. langCol = int.Parse(menu);
  39.  
  40. if (langCol < 2 || langCol > 6)
  41. {
  42. Console.WriteLine("选择无效,请重新选择.");
  43. goto MENU;
  44. }
  45. }
  46.  
  47. string excelFilePath = Directory.GetCurrentDirectory() + "\\"+excelFileName;
  48. Console.WriteLine(excelFilePath);
  49.  
  50. Application app = new Application();
  51. Workbooks wbks = app.Workbooks;
  52. _Workbook _wbk = wbks.Add(excelFilePath);
  53. Sheets shs = _wbk.Sheets;
  54. Range range_key, range_val;
  55. string key, value="";
  56. StringBuilder sb = new StringBuilder();
  57. for (int i = 1; i <= shs.Count; i++)
  58. {
  59. _Worksheet _wsh = (_Worksheet)shs.get_Item(i);
  60. int lastRow = _wsh.UsedRange.Row + _wsh.UsedRange.Rows.Count - 1;//获取最后一行行号
  61. Console.WriteLine("正在导出 工作表名称: {0} 总行数: {1}", _wsh.Name, lastRow);
  62.  
  63. for (int j = 1; j <= lastRow; j++)
  64. {
  65. range_key = _wsh.Cells[j, keyCol];
  66. if(null == range_key)
  67. continue;
  68.  
  69. key = range_key.Value;
  70. if (string.IsNullOrEmpty(key))
  71. continue;
  72.  
  73. range_val = _wsh.Cells[j, langCol];
  74. if (null != range_val && null != range_val.Value)
  75. value = range_val.Value.ToString();
  76. else
  77. value = "";
  78.  
  79. sb.AppendFormat("{0}\t{1}\r\n", key, value);
  80. }
  81.  
  82. if (sb.Length > 0)
  83. {
  84. string path = Directory.GetCurrentDirectory() + "\\" + _wsh.Name + ".txt";
  85. StreamWriter sw = File.CreateText(path);
  86. sw.AutoFlush = true;
  87. sw.Write(sb.ToString());
  88. sw.Flush();
  89. sw.Close();
  90. sw = null;
  91. }
  92. }
  93.  
  94. Console.WriteLine("语言包导出完毕!");
  95. Console.ReadKey();
  96. }
  97. }
  98. }


标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号