Converting Excel File From .csv To .xlsx

后端 未结 6 1176
清歌不尽
清歌不尽 2020-12-05 18:54

I want my application to go and find a csv excel file and convert it into a .xlsx file instead.

Here\'s what I\'m currently doing;

var fileName = @\"         


        
6条回答
  •  借酒劲吻你
    2020-12-05 19:21

    Try this class; takes in any CSV or TXT file with any delimiter including a tab and converts to Excel (.xls)

    examples:

    • convertToExcel(@"path to file", "\t", ".csv");
    • convertToExcel(@"path to file", "\|", ".txt");

      public static void convertToExcel(string fileName, string splitter, string extension)
      {
          string newFileName = fileName.Replace("." + extension, ".xls");
      
          string[] lines = File.ReadAllLines(fileName, Encoding.UTF8);
      
          int columnCounter = 0;
      
          foreach (string s in lines)
          {
              string[] ss = s.Trim().Split(Convert.ToChar(splitter));
      
              if (ss.Length > columnCounter)
                  columnCounter = ss.Length;
          }           
      
          HSSFWorkbook workbook = new HSSFWorkbook();
          var sheet = workbook.CreateSheet("Data");
          var rowIndex = 0;
          var rowExcel = sheet.CreateRow(rowIndex);
      
          foreach (string s in lines)
          {
              rowExcel = sheet.CreateRow(rowIndex);
      
              string[] ss = s.Trim().Split(Convert.ToChar(splitter));
      
              for (int i = 0; i < columnCounter; i++)
              {
                  string data = !String.IsNullOrEmpty("s") && i < ss.Length ? ss[i] : "";
                  rowExcel.CreateCell(i).SetCellType(CellType.String);
                  rowExcel.CreateCell(i).SetCellValue(data);                    
              }
      
              rowIndex++;
          }
      
          for (var i = 0; i < sheet.GetRow(0).LastCellNum; i++)
              sheet.AutoSizeColumn(i);
      
          using (FileStream file = new FileStream(newFileName, FileMode.Create, FileAccess.Write))
          {
              workbook.Write(file);
              file.Close();
          }
      }
      

提交回复
热议问题