Guest User

Untitled

a guest
Jan 18th, 2019
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. private string ConvertToXSLX(string path)
  2. {
  3. using (var fs = File.OpenRead(path))
  4. {
  5. var result = XLS_to_XLSX_Converter.Convert(fs);
  6.  
  7. // (file.xls) + x = file.xlsx
  8. path = $"{path}x";
  9.  
  10. using (var fs2 = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
  11. {
  12. fs2.Write(result, 0, result.Length);
  13. }
  14. }
  15. return path;
  16. }
  17.  
  18. public static byte[] Convert(Stream sourceStream)
  19. {
  20. var source = new HSSFWorkbook(sourceStream);
  21. var destination = new XSSFWorkbook();
  22.  
  23. for (int i = 0; i < source.NumberOfSheets; i++)
  24. {
  25. var hssfSheet = (HSSFSheet)source.GetSheetAt(i);
  26.  
  27. var xssfSheet = (XSSFSheet)destination.CreateSheet(source.GetSheetAt(i).SheetName);
  28.  
  29. CopyRows(hssfSheet, xssfSheet);
  30. }
  31.  
  32. using (var ms = new MemoryStream())
  33. {
  34. destination.Write(ms);
  35. return ms.ToArray();
  36. }
  37. }
  38.  
  39. private static void CopyRows(HSSFSheet hssfSheet, XSSFSheet destination)
  40. {
  41. for (int i = 0; i < hssfSheet.PhysicalNumberOfRows; i++)
  42. {
  43. destination.CreateRow(i);
  44.  
  45. var cells = hssfSheet.GetRow(i)?.Cells ?? new List<ICell>();
  46.  
  47. for (int j = 0; j < cells.Count; j++)
  48. {
  49. var row = destination.GetRow(i);
  50. row.CreateCell(j);
  51.  
  52. CopyCell((HSSFCell)cells[j], (XSSFCell)row.Cells[j]);
  53. }
  54. }
  55. }
  56.  
  57. private static void CopyCell(HSSFCell oldCell, XSSFCell newCell)
  58. {
  59. CopyCellValue(oldCell, newCell);
  60. }
  61.  
  62. private static void CopyCellValue(HSSFCell oldCell, XSSFCell newCell)
  63. {
  64. switch (oldCell.CellType)
  65. {
  66. case CellType.String:
  67. newCell.SetCellValue(oldCell.StringCellValue);
  68. break;
  69. case CellType.Numeric:
  70. newCell.SetCellValue(oldCell.NumericCellValue);
  71. break;
  72. case CellType.Blank:
  73. newCell.SetCellType(CellType.Blank);
  74. break;
  75. case CellType.Boolean:
  76. newCell.SetCellValue(oldCell.BooleanCellValue);
  77. break;
  78. case CellType.Error:
  79. newCell.SetCellErrorValue(oldCell.ErrorCellValue);
  80. break;
  81. default:
  82. break;
  83. }
  84. }
Add Comment
Please, Sign In to add comment