2017-04-25 56 views
0

將頭文件添加到新創建的.xlsx文件中有問題 我希望看到第一個頭文件='用戶名',第二個頭文件='密碼'。任何人都可以幫助我如何做到這一點?使用Java將頭文件添加到excel文件

XSSFWorkbook new_workbook = new XSSFWorkbook(); // create a blank workbook object 
    XSSFSheet sheet = new_workbook.createSheet("EMP_DETAILS"); // create a worksheet with caption score_details 

    // Define the SQL query 
    String sql = "SELECT login, password FROM \"Permissions\""; 
    ResultSet rs = stmt.executeQuery(sql); 

    // Create Map for Excel Data 
    Map<String, Object[]> excel_data = new HashMap<String, Object[]>(); 
    int row_counter = 0; 
    //Extract data from result set 
    while(rs.next()){ 
     row_counter = row_counter+1; 
     String login = rs.getString("login"); 
     String password = rs.getString("password"); 
     excel_data.put(Integer.toString(row_counter), new Object[] {login, password});      
    } 
    rs.close(); 

// Load data into logical worksheet 
    Set<String> keyset = excel_data.keySet(); 
    int rownum = 0; 
    for(String key : keyset){ // loop through the data and add them to the cell 
     Row row = sheet.createRow(rownum++); 
     Object [] objArr = excel_data.get(key); 
     int cellnum = 0; 
     for(Object obj : objArr){ 
      Cell cell = row.createCell(cellnum++); 
      if(obj instanceof Double) 
       cell.setCellValue((Double)obj); 
      else 
       cell.setCellValue((String)obj); 
     } 
    } 
    FileOutputStream output_file = new FileOutputStream(new File("File.xlsx")); // create XLSX file 
    new_workbook.write(output_file); // write excel document to output stream 
    output_file.close(); // close the file 
+1

那麼,你的問題實際上是什麼? –

+0

我想在excel中顯示文件標題 User |密碼 – danio900409

+0

什麼是實際結果? –

回答

0

我的$ 0.02 ...不要爲這個簡單的東西創建一個Excel文件。而是創建一個CSV文件。你寫第一行會

UserName, Password 

的頭和線後,將只是你的數據,用逗號分隔每一列。一旦文件被寫入,您就可以在Excel中輕鬆打開它並將其另存爲Excel文件。

此方法比嘗試實際編寫Excel文件更方便,更簡單。

如果你不想這樣做,你只需要創建一行,然後開始循環你的keyset,就像其他任何行一樣,併爲頭文件寫入字符串。

0

可以將此線ResultSet rs = stmt.executeQuery(sql);後使用以下代碼:

ResultSetMetaData的更正了RSMD = rs.getMetaData();

然後獲取列標題;使用如下:

String columnName1 = rsmd.getColumnName(1); // will fetch you "UserName" 
String columnName2 = rsmd.getColumnName(2); // will fetch you "Password"