【问题标题】:Spreadsheetgear - get string representation of a range of cellsSpreadsheetgear - 获取一系列单元格的字符串表示
【发布时间】:2015-05-12 00:05:09
【问题描述】:

我最近开始使用 SpreadsheetGear 来解析 Excel 文件。我需要遍历每一行并显示前 6 列的字符串表示形式。我所做的是:

    Debug.Print(ssgSheet.Cells(i,0).Text)
    Debug.Print(ssgSheet.Cells(i,1).Text)
    Debug.Print(ssgSheet.Cells(i,2).Text)
    Debug.Print(ssgSheet.Cells(i,3).Text)
    Debug.Print(ssgSheet.Cells(i,4).Text)
    Debug.Print(ssgSheet.Cells(i,5).Text)

其中“i”是工作表的当前行。这不是很漂亮,但现在如果我使用 6-liner 版本进行调试,这没什么大不了的。我也试过这个:

    Debug.Print(ssgSheet.Cells(i, 0, i, 5).Text)

但我只得到一个空行。

我只是想知道 SpreadsheetGear 中是否有一种简单的方法来获取一行或一系列单元格,并将其作为某种分隔字符串返回?我在SpreadsheetGear API site 上找不到合适的函数来执行此操作,但也许我错过了。

【问题讨论】:

    标签: spreadsheetgear


    【解决方案1】:

    数据表范围

    我不知道 SpreadsheetGear 中有任何内置函数可以从一系列单元格中获取分隔字符串。但是,有一个内置函数可以从一系列单元格中获取 DataTable。

    DataTable dt = ssgSheet.Cells[i, 0, i, 5].GetDataTable(SpreadsheetGear.Data.GetDataFlags.None);
    

    (您可能希望根据是否有列名来设置不同的标志。)

    一旦你有了一个 DataTable,你就可以使用来自this questionthis question 的代码获取一个分隔字符串。

    以 CSV 格式保存范围到流

    另一种选择是将 CSV 格式的范围保存到 Stream,然后从 Stream 中获取分隔字符串。

    using (System.IO.MemoryStream mstream = new System.IO.MemoryStream())
    {
      ssgSheet.Cells[i, 0, i, 5].SaveToStream(mstream, SpreadsheetGear.FileFormat.CSV);
      mstream.Position = 0;
      System.IO.StreamReader reader = new System.IO.StreamReader(mstream);
      Debug.Print(reader.ReadToEnd());
    }
    

    【讨论】:

      【解决方案2】:
      public void FormatedExport(string destinationFileName, ref DataTable sourceTable, ref FileExportParameters fileExportParameters)
      {
          // Create a new workbook and worksheet.
          IWorkbook _workbook = SpreadsheetGear.Factory.GetWorkbook();
          IWorksheet _worksheet = _workbook.Worksheets["Sheet1"];
      
          // Get the top left cell for the DataTable.
          SpreadsheetGear.IRange _range = _worksheet.Cells["A1"];
      
          // Copy the DataTable to the worksheet range.
          _range.CopyFromDataTable(sourceTable, SpreadsheetGear.Data.SetDataFlags.None);
      
          // Auto size all worksheet columns which contain data
          _worksheet.UsedRange.Columns.AutoFit();
      
          // Stream the Excel spreadsheet to the client in a format
          // compatible with Excel 97/2000/XP/2003/2007/2010.
          if (fileExportParameters.exportType == ExportType.Excel)
             _workbook.SaveAs(destinationFileName, SpreadsheetGear.FileFormat.Excel8);
          else if (fileExportParameters.exportType == ExportType.FormatedText)
            _workbook.SaveAs(destinationFileName, SpreadsheetGear.FileFormat.CSV);
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-12
        • 2021-05-30
        • 2013-07-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多