我将数据从数据库存储到ArrayList。并从ArrayList获得数据以将其写入Excel文件中以供用户下载。当我写入excel文件时,它将完美写入。但是当我写入更多数据时,称为“ total”的最后一行出现在其他lines.coding内,如下所示。
public String excel_missedcall(List<datefilter> result1){
Date date = new Date(System.currentTimeMillis());
String download_file="";
Properties prop = new Properties();
InputStream input = null;
String link="";
String linkfilepath="";
//read file name from properties file
try {
String filename = "config.properties";
input = MainController.class.getClassLoader().getResourceAsStream(
filename);
if (input == null) {
System.out.println("Sorry, unable to find " + filename);
}
// load a properties file from class path, inside static method
prop.load(input);
String filepath=prop.getProperty("missedcall_filePath");
download_file=filepath+"missedcall_"+date.getTime()+".xlsx";
link=prop.getProperty("missedcall_downloadfilePath");
linkfilepath=link+"missedcall_"+date.getTime()+".xlsx";
int total=0;
//create excel sheet
//Blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank sheet
XSSFSheet sheet= workbook.createSheet("Missedcall");
//This data needs to be written (Object[])
Map<String, Object[]> data = new TreeMap<String, Object[]>();
data.put("1", new Object[] {"Date", "TotalCalls"});
for(int i=0;i<result1.size();i++){
data.put(""+(i+2),new Object[] {result1.get(i).getMisscall_date(),Integer.parseInt(result1.get(i).getSum_misscall())});
total+=Integer.parseInt( result1.get(i).getSum_misscall());
//System.out.println("**********1*********"+(i+2));
}
data.put(""+(result1.size()+2), new Object[] {"Total", total});
//Iterate over data and write to sheet
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset)
{
System.out.println("*********1**********"+key);
Row row = sheet.createRow(rownum++);
System.out.println("*********2**********"+rownum);
Object [] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr)
{
Cell cell = row.createCell(cellnum++);
if(obj instanceof String)
cell.setCellValue((String)obj);
else if(obj instanceof Integer)
cell.setCellValue((Integer)obj);
}
}
try
{
//Write the workbook in file system
FileOutputStream out1 = new FileOutputStream(new File(download_file));
workbook.write(out1);
out1.close();
System.out.println("xlsx written successfully on disk.");
}
catch (Exception e)
{
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return linkfilepath;
}
Excel文件的输出是:
Date TotalCalls
2015-08-28 1895
2015-08-29 599
2015-08-30 354
2015-08-31 2028
Total 6712
2015-08-20 0
2015-08-21 0
2015-08-22 2
2015-08-23 12
2015-08-24 22
2015-08-25 324
2015-08-26 878
2015-08-27 598
请帮我。
最佳答案
您将String用作键,替换下面的行
Map<String, Object[]> data = new TreeMap<String, Object[]>();
与
Map<Integer, Object[]> data = new TreeMap<Integer, Object[]>();
关于mysql - 用Java编写的Excel文件更改顺序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32644715/