我有下面的代码,它的作用基本上是从我的表格模型中获取我的数据并将其放入电子表格中。但是,在导出数据时,数据并没有按照我在对表格进行排序时指定的顺序保存:
这是从另一个对表格行进行排序并执行方法 saveSingleTableAsExcel(); 的方法定义如下。导出数据:
.......
sorter = new TableRowSorter<>(tableR.getModel());
tableR.setRowSorter(sorter);
sortKeys = new ArrayList<>();
int columnIndexToSort = 0;
sortKeys.add(new RowSorter.SortKey(columnIndexToSort, SortOrder.ASCENDING));
sorter.setSortKeys(sortKeys);
sorter.sort();
saveSingleTableAsExcel();
…………
public void saveSingleTableAsExcel() throws FileNotFoundException{
Map<String,TableModel> models = new HashMap<String,TableModel>();
models.put("Sheet1", modelR);
saveTablesAsExcel(models);
}
public static void saveTablesAsExcel(Map<String,TableModel> models) throws FileNotFoundException{
HSSFWorkbook wb = new HSSFWorkbook();
for (String sheetName : models.keySet()){
createSheet(wb, models.get(sheetName), sheetName);
}
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HHmmss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime())); //2014/08/06 16:00:22
//FileOutputStream out = null;
FileOutputStream out = new FileOutputStream("C:\\Users\\tester.xls");
try {
wb.write(out);
out.close();
} catch (IOException e) {
}
}
/**
* Create a Sheet in the workbook using data from the TableModel
*
* @param wb
* @param model
* @param sheetName
*/
private static void createSheet(HSSFWorkbook wb, TableModel model, String sheetName){
Sheet sheet = wb.createSheet(sheetName);
Row headerRow = sheet.createRow(0);
headerRow.setHeightInPoints(12.75f);
HSSFFont boldFont = wb.createFont();
boldFont.setFontHeightInPoints((short)22);
boldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
HSSFCellStyle headerStyle = wb.createCellStyle();
// Create the header cells
int numColumns = model.getColumnCount();
for (int col=0; col<numColumns; col++) {
Cell cell = headerRow.createCell(col);
cell.setCellValue(model.getColumnName(col));
cell.setCellStyle(headerStyle);
}
// Set the cell values
int numRows = model.getRowCount();
for (int row=0; row<numRows; row++){
Row sheetRow = sheet.createRow(row+1); // account for header row (0)
for (int col=0; col<numColumns; col++) {
Cell cell = sheetRow.createCell(col);
Object val = model.getValueAt(row, col);
if (val instanceof Number){
cell.setCellValue((double)val);
}
else if (val instanceof Boolean){
cell.setCellValue((Boolean)val);
}
else if (val instanceof String){
cell.setCellValue(((String)val));
}
else if (val instanceof Date){
cell.setCellValue((Date)val);
}
// else {
// cell.setCellValue(val.toString());
// }
}
}
}
如何保留与模型相同的顺序,按第一列(第 0 列)排序?