0

我正在计划一个 MS Small Basic 程序,我将在其中带来大量数字作为输入。如何将 Excel 表中的数字表读取到程序中?安蒂

4

1 回答 1

0

艰难之路——

编程的伟大之处在于几乎任何语言都可以做几乎任何事情。Small Basic 也不例外。如果您不介意与其他语言相比会看到巨大的时间冲击,您可以对文件做任何您想做的事情。

为了证明这一点,我编写了一个示例,该示例将 Excel 表加载到 Small Basic 中的二维数组中。

要将 Excel 文件导入 Small Basic,您需要做的第一件事是以易于处理的格式保存文件。下面的示例假定文件已以逗号分隔的 CSV 格式保存。按照这种格式,每个单元格都以逗号结尾,每一行都以 CR-LF 组合结尾。剩下的只是逐个字符解析信息的问题。

'Reading an Excel Table saved as a CSV (comma seperated) file. 
TextWindow.Show()

LoadFile()
TextWindow.WriteLine("File Size = " + Text.GetLength(DataIn))
ParseFile()
TextWindow.WriteLine("Rows = " + rows + ",  Columns = " + cols)
DisplayTable()

'---------------------------------------------------------------

'Read the contents of the CSV file into memory
Sub LoadFile
  filename = Program.Directory
  filename = filename + "\excelintoSB.csv"

  DataIn = File.ReadContents(filename)
EndSub

'Parse the file contents, looking for commas and line breaks to separate the cells. 
Sub ParseFile
  row = 1
  col = 1
  cell = ""

  For i =1 To Text.GetLength(DataIn)  'Look at each character in the file
    ch = Text.GetSubText(DataIn,i,1)
    'Is it a comma or a cariage return? Store the Cell
    If ch = "," or text.GetCharacterCode(ch) = 13 then
      table[row][col] = cell
      cell = ""
      If text.GetCharacterCode(ch) = 13 Then 'end of row, start a new one
        row = row + 1
        col = 1
      Else 'New Cell, current row
        col = col + 1
        If col > maxCol then 'Keep track of how many columns we have encountered
          maxCol = col
        endif
      endif
    ElseIf text.GetCharacterCode(ch) <> 10 then 'build the cell, ignoring line feeds.
      cell = cell + ch
    EndIf
  EndFor
  rows = row - 1
  cols = maxCol
EndSub

'Display the table in row / column format
Sub DisplayTable
  TextWindow.WriteLine("The Table --- ")
  For i = 1 To rows
    TextWindow.Write("[ ")
    For j = 1 To cols
      TextWindow.Write(table[i][j] + " ")
    EndFor
    TextWindow.WriteLine("]")
  EndFor
EndSub

以下是我测试它的文件,最初是在 Excel 中创建并保存为 CSV:

1a,1b,1c,1d
2a,2b,2c,2d
3a,3b,3c,3d

享受!

于 2017-04-13T18:51:21.353 回答