我有一个代码将MySQL表导出到excel文件。我想导出excel文件,其中包含用户可以理解的列名。我如何设置这些新列名。我的代码如下所示。谢谢。
public Response getEventsAsExcel(@Context HttpServletResponse response) throws Throwable {
DataReader reader = getEvents();
ExcelDocument excelDocument = new ExcelDocument();
DataWriter writer = new ExcelWriter(excelDocument).setFieldNamesInFirstRow(true);
JobTemplate.DEFAULT.transfer(reader, writer);
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=\"export.xls\"");
OutputStream outputStream = response.getOutputStream();
excelDocument.save(outputStream);
return Response.ok().build();
}
答案 0 :(得分:0)
以下是我正在使用的示例代码。
try {
response.setContentType("application/vnd.ms-excel");
String reportName = "excelname_.xls";
response.setHeader("Content-disposition", "attachment; filename=" + reportName);
ArrayList<String> rows = new ArrayList<String>();
rows.add("col1 name");
rows.add("\t");
rows.add("col2 name");
rows.add("\t");
rows.add("col3 name");
rows.add("\n");
for (int i = 0; i < 5; i++) {
rows.add("col1 data");
rows.add("\t");
rows.add("col2 data");
rows.add("\t");
rows.add("col3 data");
rows.add("\n");
}
Iterator<String> iter = rows.iterator();
while (iter.hasNext()) {
String outputString = (String) iter.next();
response.getOutputStream().print(outputString);
}
response.getOutputStream().flush();
} catch (IOException e) {
e.printStackTrace();
}
您可以使用简单的SQL查询将mysql表导出为excel。
String filename = "d:/outfile.xls";//name of excel file here
String tablename = "abc";//name of table here
stmt.executeQuery("SELECT * INTO OUTFILE \"" + filename + "\" FROM " + tablename);//now execute it.