XLS2CSV.cs 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6. using NPOI.HSSF.UserModel;
  7. using CommonLang.Xml;
  8. using System.Xml;
  9. using CommonLang.Concurrent;
  10. using CommonLang.XCSV;
  11. namespace GameEditorPlugin.Utils
  12. {
  13. public class XLS2XCSV
  14. {
  15. public readonly XCSVMeta Meta;
  16. public XmlDocument Doc { get { return Meta.Doc; } }
  17. public FileInfo XlsFile { get { return Meta.XlsFile; } }
  18. public float Percent { get { lock (this) { return mReaded / (float)mTotal; } } }
  19. private HSSFWorkbook Workbook;
  20. private int mTotal = 1;
  21. private int mReaded = 0;
  22. public XLS2XCSV(FileInfo ff)
  23. {
  24. lock (this)
  25. {
  26. Meta.Doc = new XmlDocument();
  27. Meta.XlsFile = ff;
  28. this.mTotal = 0;
  29. using (FileStream ms = new FileStream(XlsFile.FullName, FileMode.Open, FileAccess.Read))
  30. {
  31. Workbook = new HSSFWorkbook(ms);
  32. for (int si = 0; si < Workbook.NumberOfSheets; si++)
  33. {
  34. HSSFSheet sheet = Workbook.GetSheetAt(si) as HSSFSheet;
  35. mTotal += (sheet.LastRowNum - sheet.FirstRowNum + 1);
  36. }
  37. }
  38. }
  39. }
  40. public void Load(AtomicFloat percent = null)
  41. {
  42. float d = 1f / mTotal;
  43. XmlElement xml = Doc.CreateElement("workbook");
  44. xml.SetAttribute("name", XlsFile.Name);
  45. this.Doc.AppendChild(xml);
  46. for (int si = 0; si < Workbook.NumberOfSheets; si++)
  47. {
  48. HSSFSheet sheet = Workbook.GetSheetAt(si) as HSSFSheet;
  49. XmlElement xsheet = Doc.CreateElement("sheet");
  50. xsheet.SetAttribute("name", sheet.SheetName);
  51. for (int r = sheet.FirstRowNum; r <= sheet.LastRowNum; r++)
  52. {
  53. HSSFRow row = sheet.GetRow(r) as HSSFRow;
  54. if (row != null)
  55. {
  56. XmlElement xrow = Doc.CreateElement("row");
  57. xrow.SetAttribute("r", r.ToString());
  58. for (int c = row.FirstCellNum; c <= row.LastCellNum; c++)
  59. {
  60. HSSFCell cell = row.GetCell(c) as HSSFCell;
  61. if (cell != null)
  62. {
  63. XmlElement xcell = Doc.CreateElement("cell");
  64. xcell.InnerText = cell.ToString();
  65. xcell.SetAttribute("r", r.ToString());
  66. xcell.SetAttribute("c", c.ToString());
  67. xrow.AppendChild(xcell);
  68. }
  69. }
  70. xsheet.AppendChild(xrow);
  71. }
  72. mReaded += 1;
  73. if (percent != null)
  74. {
  75. percent.AddAndGet(d);
  76. }
  77. }
  78. xml.AppendChild(xsheet);
  79. }
  80. }
  81. public void Save()
  82. {
  83. Save(XlsFile.Directory + "/" + Path.GetFileNameWithoutExtension(XlsFile.FullName) + ".xcsv");
  84. }
  85. public void Save(string path)
  86. {
  87. XmlUtil.SaveXML(new FileStream(path, FileMode.Create, FileAccess.Write), Doc, true);
  88. }
  89. }
  90. }