Excel file format converter












4












$begingroup$


I'm using C# .NET Core 2.1 and Excel lib DotnetCore.NPOI



I'm converting xls file to xlsx by loading xls and copying sheet by sheet, cell by cell to xlsx - How can I improve performance / ram usage here?



private string ConvertToXSLX(string path) 
{
using (var fs = File.OpenRead(path))
{
var result = XLS_to_XLSX_Converter.Convert(fs);

// (file.xls) + x = file.xlsx
path = $"{path}x";

using (var fs2 = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
{
fs2.Write(result, 0, result.Length);
}
}
return path;
}




public static byte Convert(Stream sourceStream)
{
var source = new HSSFWorkbook(sourceStream);
var destination = new XSSFWorkbook();

for (int i = 0; i < source.NumberOfSheets; i++)
{
var hssfSheet = (HSSFSheet)source.GetSheetAt(i);

var xssfSheet = (XSSFSheet)destination.CreateSheet(source.GetSheetAt(i).SheetName);

CopyRows(hssfSheet, xssfSheet);
}

using (var ms = new MemoryStream())
{
destination.Write(ms);
return ms.ToArray();
}
}

private static void CopyRows(HSSFSheet hssfSheet, XSSFSheet destination)
{
for (int i = 0; i < hssfSheet.PhysicalNumberOfRows; i++)
{
destination.CreateRow(i);

var cells = hssfSheet.GetRow(i)?.Cells ?? new List<ICell>();

for (int j = 0; j < cells.Count; j++)
{
var row = destination.GetRow(i);
row.CreateCell(j);

CopyCell((HSSFCell)cells[j], (XSSFCell)row.Cells[j]);
}
}
}

private static void CopyCell(HSSFCell oldCell, XSSFCell newCell)
{
CopyCellValue(oldCell, newCell);
}

private static void CopyCellValue(HSSFCell oldCell, XSSFCell newCell)
{
switch (oldCell.CellType)
{
case CellType.String:
newCell.SetCellValue(oldCell.StringCellValue);
break;
case CellType.Numeric:
newCell.SetCellValue(oldCell.NumericCellValue);
break;
case CellType.Blank:
newCell.SetCellType(CellType.Blank);
break;
case CellType.Boolean:
newCell.SetCellValue(oldCell.BooleanCellValue);
break;
case CellType.Error:
newCell.SetCellErrorValue(oldCell.ErrorCellValue);
break;
default:
break;
}
}


enter image description here



enter image description here










share|improve this question











$endgroup$

















    4












    $begingroup$


    I'm using C# .NET Core 2.1 and Excel lib DotnetCore.NPOI



    I'm converting xls file to xlsx by loading xls and copying sheet by sheet, cell by cell to xlsx - How can I improve performance / ram usage here?



    private string ConvertToXSLX(string path) 
    {
    using (var fs = File.OpenRead(path))
    {
    var result = XLS_to_XLSX_Converter.Convert(fs);

    // (file.xls) + x = file.xlsx
    path = $"{path}x";

    using (var fs2 = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
    {
    fs2.Write(result, 0, result.Length);
    }
    }
    return path;
    }




    public static byte Convert(Stream sourceStream)
    {
    var source = new HSSFWorkbook(sourceStream);
    var destination = new XSSFWorkbook();

    for (int i = 0; i < source.NumberOfSheets; i++)
    {
    var hssfSheet = (HSSFSheet)source.GetSheetAt(i);

    var xssfSheet = (XSSFSheet)destination.CreateSheet(source.GetSheetAt(i).SheetName);

    CopyRows(hssfSheet, xssfSheet);
    }

    using (var ms = new MemoryStream())
    {
    destination.Write(ms);
    return ms.ToArray();
    }
    }

    private static void CopyRows(HSSFSheet hssfSheet, XSSFSheet destination)
    {
    for (int i = 0; i < hssfSheet.PhysicalNumberOfRows; i++)
    {
    destination.CreateRow(i);

    var cells = hssfSheet.GetRow(i)?.Cells ?? new List<ICell>();

    for (int j = 0; j < cells.Count; j++)
    {
    var row = destination.GetRow(i);
    row.CreateCell(j);

    CopyCell((HSSFCell)cells[j], (XSSFCell)row.Cells[j]);
    }
    }
    }

    private static void CopyCell(HSSFCell oldCell, XSSFCell newCell)
    {
    CopyCellValue(oldCell, newCell);
    }

    private static void CopyCellValue(HSSFCell oldCell, XSSFCell newCell)
    {
    switch (oldCell.CellType)
    {
    case CellType.String:
    newCell.SetCellValue(oldCell.StringCellValue);
    break;
    case CellType.Numeric:
    newCell.SetCellValue(oldCell.NumericCellValue);
    break;
    case CellType.Blank:
    newCell.SetCellType(CellType.Blank);
    break;
    case CellType.Boolean:
    newCell.SetCellValue(oldCell.BooleanCellValue);
    break;
    case CellType.Error:
    newCell.SetCellErrorValue(oldCell.ErrorCellValue);
    break;
    default:
    break;
    }
    }


    enter image description here



    enter image description here










    share|improve this question











    $endgroup$















      4












      4








      4





      $begingroup$


      I'm using C# .NET Core 2.1 and Excel lib DotnetCore.NPOI



      I'm converting xls file to xlsx by loading xls and copying sheet by sheet, cell by cell to xlsx - How can I improve performance / ram usage here?



      private string ConvertToXSLX(string path) 
      {
      using (var fs = File.OpenRead(path))
      {
      var result = XLS_to_XLSX_Converter.Convert(fs);

      // (file.xls) + x = file.xlsx
      path = $"{path}x";

      using (var fs2 = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
      {
      fs2.Write(result, 0, result.Length);
      }
      }
      return path;
      }




      public static byte Convert(Stream sourceStream)
      {
      var source = new HSSFWorkbook(sourceStream);
      var destination = new XSSFWorkbook();

      for (int i = 0; i < source.NumberOfSheets; i++)
      {
      var hssfSheet = (HSSFSheet)source.GetSheetAt(i);

      var xssfSheet = (XSSFSheet)destination.CreateSheet(source.GetSheetAt(i).SheetName);

      CopyRows(hssfSheet, xssfSheet);
      }

      using (var ms = new MemoryStream())
      {
      destination.Write(ms);
      return ms.ToArray();
      }
      }

      private static void CopyRows(HSSFSheet hssfSheet, XSSFSheet destination)
      {
      for (int i = 0; i < hssfSheet.PhysicalNumberOfRows; i++)
      {
      destination.CreateRow(i);

      var cells = hssfSheet.GetRow(i)?.Cells ?? new List<ICell>();

      for (int j = 0; j < cells.Count; j++)
      {
      var row = destination.GetRow(i);
      row.CreateCell(j);

      CopyCell((HSSFCell)cells[j], (XSSFCell)row.Cells[j]);
      }
      }
      }

      private static void CopyCell(HSSFCell oldCell, XSSFCell newCell)
      {
      CopyCellValue(oldCell, newCell);
      }

      private static void CopyCellValue(HSSFCell oldCell, XSSFCell newCell)
      {
      switch (oldCell.CellType)
      {
      case CellType.String:
      newCell.SetCellValue(oldCell.StringCellValue);
      break;
      case CellType.Numeric:
      newCell.SetCellValue(oldCell.NumericCellValue);
      break;
      case CellType.Blank:
      newCell.SetCellType(CellType.Blank);
      break;
      case CellType.Boolean:
      newCell.SetCellValue(oldCell.BooleanCellValue);
      break;
      case CellType.Error:
      newCell.SetCellErrorValue(oldCell.ErrorCellValue);
      break;
      default:
      break;
      }
      }


      enter image description here



      enter image description here










      share|improve this question











      $endgroup$




      I'm using C# .NET Core 2.1 and Excel lib DotnetCore.NPOI



      I'm converting xls file to xlsx by loading xls and copying sheet by sheet, cell by cell to xlsx - How can I improve performance / ram usage here?



      private string ConvertToXSLX(string path) 
      {
      using (var fs = File.OpenRead(path))
      {
      var result = XLS_to_XLSX_Converter.Convert(fs);

      // (file.xls) + x = file.xlsx
      path = $"{path}x";

      using (var fs2 = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
      {
      fs2.Write(result, 0, result.Length);
      }
      }
      return path;
      }




      public static byte Convert(Stream sourceStream)
      {
      var source = new HSSFWorkbook(sourceStream);
      var destination = new XSSFWorkbook();

      for (int i = 0; i < source.NumberOfSheets; i++)
      {
      var hssfSheet = (HSSFSheet)source.GetSheetAt(i);

      var xssfSheet = (XSSFSheet)destination.CreateSheet(source.GetSheetAt(i).SheetName);

      CopyRows(hssfSheet, xssfSheet);
      }

      using (var ms = new MemoryStream())
      {
      destination.Write(ms);
      return ms.ToArray();
      }
      }

      private static void CopyRows(HSSFSheet hssfSheet, XSSFSheet destination)
      {
      for (int i = 0; i < hssfSheet.PhysicalNumberOfRows; i++)
      {
      destination.CreateRow(i);

      var cells = hssfSheet.GetRow(i)?.Cells ?? new List<ICell>();

      for (int j = 0; j < cells.Count; j++)
      {
      var row = destination.GetRow(i);
      row.CreateCell(j);

      CopyCell((HSSFCell)cells[j], (XSSFCell)row.Cells[j]);
      }
      }
      }

      private static void CopyCell(HSSFCell oldCell, XSSFCell newCell)
      {
      CopyCellValue(oldCell, newCell);
      }

      private static void CopyCellValue(HSSFCell oldCell, XSSFCell newCell)
      {
      switch (oldCell.CellType)
      {
      case CellType.String:
      newCell.SetCellValue(oldCell.StringCellValue);
      break;
      case CellType.Numeric:
      newCell.SetCellValue(oldCell.NumericCellValue);
      break;
      case CellType.Blank:
      newCell.SetCellType(CellType.Blank);
      break;
      case CellType.Boolean:
      newCell.SetCellValue(oldCell.BooleanCellValue);
      break;
      case CellType.Error:
      newCell.SetCellErrorValue(oldCell.ErrorCellValue);
      break;
      default:
      break;
      }
      }


      enter image description here



      enter image description here







      c# performance excel






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 2 hours ago









      200_success

      129k15152415




      129k15152415










      asked 20 hours ago









      JoeltyJoelty

      233




      233






















          1 Answer
          1






          active

          oldest

          votes


















          4












          $begingroup$

          You're writing to a MemoryStream only to get a byte to write to another stream, you can definitely avoid this intermediate conversion:



          private string ConvertToXSLX(string inputPath) 
          {
          string outputPath = Path.ChangeExtension(inputPath, ".xlsx");

          using (var input = File.OpenRead(inputPath))
          using (var output = new FileStream(outputPath, FileMode.OpenOrCreate, FileAccess.Write))
          {
          XLS_to_XLSX_Converter.Convert(input, output);
          }

          return outputPath;
          }


          The change in Convert() should be trivial.



          Also note that I'm using Path.ChangeExtension() instead of manually adding a character, code is clear without any comment and it handles special cases for you (for example a trailing space).





          In CopyRows() you create an empty List<ICell>, you do not need to and you can avoid the initial allocation simply using Enumerable.Empty<ICell>() (and changing your code to work with an enumeration) or - at least - reusing the same empty object (move it outside the loop and create it with an initial capacity of 0).





          In CopyCellValue() you have an empty default case for your switch. It's a good thing to always have default but it has a purpose: detect unknown cases. If you put a break then you're silently ignoring them. Is it on purpose? Write a comment to explain you ignore unknown cells. It's an error? Throw an exception.





          I never used DotnetCore.NPOI then I can't comment about the way you use it, be sure to dispose all the intermediate IDisposable objects.






          share|improve this answer









          $endgroup$













            Your Answer





            StackExchange.ifUsing("editor", function () {
            return StackExchange.using("mathjaxEditing", function () {
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            });
            });
            }, "mathjax-editing");

            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "196"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f211751%2fexcel-file-format-converter%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            4












            $begingroup$

            You're writing to a MemoryStream only to get a byte to write to another stream, you can definitely avoid this intermediate conversion:



            private string ConvertToXSLX(string inputPath) 
            {
            string outputPath = Path.ChangeExtension(inputPath, ".xlsx");

            using (var input = File.OpenRead(inputPath))
            using (var output = new FileStream(outputPath, FileMode.OpenOrCreate, FileAccess.Write))
            {
            XLS_to_XLSX_Converter.Convert(input, output);
            }

            return outputPath;
            }


            The change in Convert() should be trivial.



            Also note that I'm using Path.ChangeExtension() instead of manually adding a character, code is clear without any comment and it handles special cases for you (for example a trailing space).





            In CopyRows() you create an empty List<ICell>, you do not need to and you can avoid the initial allocation simply using Enumerable.Empty<ICell>() (and changing your code to work with an enumeration) or - at least - reusing the same empty object (move it outside the loop and create it with an initial capacity of 0).





            In CopyCellValue() you have an empty default case for your switch. It's a good thing to always have default but it has a purpose: detect unknown cases. If you put a break then you're silently ignoring them. Is it on purpose? Write a comment to explain you ignore unknown cells. It's an error? Throw an exception.





            I never used DotnetCore.NPOI then I can't comment about the way you use it, be sure to dispose all the intermediate IDisposable objects.






            share|improve this answer









            $endgroup$


















              4












              $begingroup$

              You're writing to a MemoryStream only to get a byte to write to another stream, you can definitely avoid this intermediate conversion:



              private string ConvertToXSLX(string inputPath) 
              {
              string outputPath = Path.ChangeExtension(inputPath, ".xlsx");

              using (var input = File.OpenRead(inputPath))
              using (var output = new FileStream(outputPath, FileMode.OpenOrCreate, FileAccess.Write))
              {
              XLS_to_XLSX_Converter.Convert(input, output);
              }

              return outputPath;
              }


              The change in Convert() should be trivial.



              Also note that I'm using Path.ChangeExtension() instead of manually adding a character, code is clear without any comment and it handles special cases for you (for example a trailing space).





              In CopyRows() you create an empty List<ICell>, you do not need to and you can avoid the initial allocation simply using Enumerable.Empty<ICell>() (and changing your code to work with an enumeration) or - at least - reusing the same empty object (move it outside the loop and create it with an initial capacity of 0).





              In CopyCellValue() you have an empty default case for your switch. It's a good thing to always have default but it has a purpose: detect unknown cases. If you put a break then you're silently ignoring them. Is it on purpose? Write a comment to explain you ignore unknown cells. It's an error? Throw an exception.





              I never used DotnetCore.NPOI then I can't comment about the way you use it, be sure to dispose all the intermediate IDisposable objects.






              share|improve this answer









              $endgroup$
















                4












                4








                4





                $begingroup$

                You're writing to a MemoryStream only to get a byte to write to another stream, you can definitely avoid this intermediate conversion:



                private string ConvertToXSLX(string inputPath) 
                {
                string outputPath = Path.ChangeExtension(inputPath, ".xlsx");

                using (var input = File.OpenRead(inputPath))
                using (var output = new FileStream(outputPath, FileMode.OpenOrCreate, FileAccess.Write))
                {
                XLS_to_XLSX_Converter.Convert(input, output);
                }

                return outputPath;
                }


                The change in Convert() should be trivial.



                Also note that I'm using Path.ChangeExtension() instead of manually adding a character, code is clear without any comment and it handles special cases for you (for example a trailing space).





                In CopyRows() you create an empty List<ICell>, you do not need to and you can avoid the initial allocation simply using Enumerable.Empty<ICell>() (and changing your code to work with an enumeration) or - at least - reusing the same empty object (move it outside the loop and create it with an initial capacity of 0).





                In CopyCellValue() you have an empty default case for your switch. It's a good thing to always have default but it has a purpose: detect unknown cases. If you put a break then you're silently ignoring them. Is it on purpose? Write a comment to explain you ignore unknown cells. It's an error? Throw an exception.





                I never used DotnetCore.NPOI then I can't comment about the way you use it, be sure to dispose all the intermediate IDisposable objects.






                share|improve this answer









                $endgroup$



                You're writing to a MemoryStream only to get a byte to write to another stream, you can definitely avoid this intermediate conversion:



                private string ConvertToXSLX(string inputPath) 
                {
                string outputPath = Path.ChangeExtension(inputPath, ".xlsx");

                using (var input = File.OpenRead(inputPath))
                using (var output = new FileStream(outputPath, FileMode.OpenOrCreate, FileAccess.Write))
                {
                XLS_to_XLSX_Converter.Convert(input, output);
                }

                return outputPath;
                }


                The change in Convert() should be trivial.



                Also note that I'm using Path.ChangeExtension() instead of manually adding a character, code is clear without any comment and it handles special cases for you (for example a trailing space).





                In CopyRows() you create an empty List<ICell>, you do not need to and you can avoid the initial allocation simply using Enumerable.Empty<ICell>() (and changing your code to work with an enumeration) or - at least - reusing the same empty object (move it outside the loop and create it with an initial capacity of 0).





                In CopyCellValue() you have an empty default case for your switch. It's a good thing to always have default but it has a purpose: detect unknown cases. If you put a break then you're silently ignoring them. Is it on purpose? Write a comment to explain you ignore unknown cells. It's an error? Throw an exception.





                I never used DotnetCore.NPOI then I can't comment about the way you use it, be sure to dispose all the intermediate IDisposable objects.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 18 hours ago









                Adriano RepettiAdriano Repetti

                9,77911441




                9,77911441






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Code Review Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    Use MathJax to format equations. MathJax reference.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f211751%2fexcel-file-format-converter%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Сан-Квентин

                    Алькесар

                    Josef Freinademetz