示例#1
0
  private static byte[] getCsv(
      ResultSet rs,
      String delimiter,
      String enclosing,
      boolean printHeader,
      List<KeyValue<String, String>> additionalColumns) {
    Integer width = 0;

    Integer height = 0;
    StringBuilder sb = new StringBuilder();
    String addCols = null;
    ResultSetHelper rsch = new ResultSetHelper();
    try {
      while (rs.next()) {
        if (height == 0) {
          width = rs.getMetaData().getColumnCount();
          String header = null;
          if (additionalColumns != null) {
            for (KeyValue<String, String> kv : additionalColumns) {
              if (header == null) {
                header = "";
                addCols = "";
              } else {
                header += delimiter;
              }
              header += enclosing + kv.getKey() + enclosing;
              addCols += enclosing + kv.getValue() + enclosing + delimiter;
            }
          }
          for (int s = 0; s < width; s++) {
            if (header != null) {
              header += delimiter;
            } else {
              header = "";
            }
            header += enclosing + rs.getMetaData().getColumnName(s + 1) + enclosing;
          }
          if (header != null && printHeader) {
            header += "\r\n";
            sb.append(header);
          }
        }
        if (addCols != null) {
          sb.append(addCols);
        }
        for (int i = 0; i < width; i++) {
          int colType = rs.getMetaData().getColumnType(i + 1);
          String content = rsch.getValue(rs, colType, i + 1);
          if (content == null) {
            content = "";
          }
          if (i > 0) {
            sb.append(delimiter);
          }
          content = content.replace("\"", "\"\"");
          sb.append(enclosing + content + enclosing);
        }
        sb.append("\r\n");
        height++;
      }
      return sb.toString().getBytes(SaikuProperties.webExportCsvTextEncoding); // $NON-NLS-1$
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return new byte[0];
  }