【问题标题】:Reading column format with cfspreadsheet使用 cfspreadsheet 读取列格式
【发布时间】:2012-01-27 03:09:05
【问题描述】:

当您使用cfspreadsheet 读取电子表格中的列或单元格时,是否可以获得数据类型或格式?

我正在将电子表格数据从 Excel 电子表格转换为数据库表。到目前为止,我只是将所有内容都格式化为 varchars,但如果我可以将日期指定为日期,将整数指定为整数,那就更好了。

【问题讨论】:

    标签: types coldfusion format cfspreadsheet


    【解决方案1】:

    很遗憾,没有使用cfspreadsheet 或内置的电子表格函数。它们只返回显示的内容,而不是基础值。但是,您可以通过点击底层 POI workbook 来创建自己的。

    需要注意的几点:

    • 与数据库表不同,电子表格列可以包含多种数据类型。仅仅因为第一个单元格包含日期并不能保证该列中的 所有 单元格也包含日期。因此,与任何导入一样,请务必在将所有值插入数据库表之前对其进行验证。
    • 这些方法仅包括填充行和单元格。跳过空白行和单元格。所以列值并不总是连续的。
    • 工作表、行和列索引从零 (0) 开始

    要进行处理,只需获取所需的工作表并遍历行和单元格。当您遍历列时,检查单元格类型并提取原始值(即日期、字符串、数字......)

    来源:Busy Developers' Guide to HSSF and XSSF Features

    <cfscript>
    // get the sheet you want to read
    cfSheet = SpreadSheetRead("c:/path/to/somefile.xls"); 
    workbook = cfSheet.getWorkBook();
    sheetIndex = workbook.getActiveSheetIndex();
    sheet = workbook.getSheetAt( sheetIndex );
    
    // utility used to distinguish between dates and numbers
    dateUtil = createObject("java", "org.apache.poi.ss.usermodel.DateUtil");
    
    // process the rows and columns
    rows = sheet.rowIterator();
    while (rows.hasNext()) {
        currentRow = rows.next();
        data = {}; 
    
        cells = currentRow.cellIterator();
        while (cells.hasNext()) { 
            currentCell = cells.next();
    
            col = {};
            col.value  = "";
            col.type   = "";
            col.column = currentCell.getColumnIndex()+ 1;
            col.row    = currentCell.getRowIndex()+ 1;
    
            if (currentCell.getCellType() EQ currentCell.CELL_TYPE_STRING) {
                   col.value = currentCell.getRichStringCellValue().getString();
                col.type = "string";
            }
            else if (currentCell.getCellType() EQ currentCell.CELL_TYPE_NUMERIC) {
                if (DateUtil.isCellDateFormatted(currentCell)) {
                     col.value = currentCell.getDateCellValue();
                     col.type = "date";
                } 
                else {
                     col.value = currentCell.getNumericCellValue();
                     col.type = "number";
                }
            }
            else if (currentCell.getCellType() EQ currentCell.CELL_TYPE_BOOLEAN) {
                col.value = currentCell.getBooleanCellValue();
                col.type = "boolean";
            }
            // ... handle other types CELL_TYPE_BLANK, CELL_TYPE_ERROR, CELL_TYPE_FORMULA
    
            data["COL"& col.column] = col;
        }
    
        // this row is finished. display all values
        WriteDump(data);
    }
    </cfscript>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多