I have a code that exports MySQL table to excel file.I want to export the excel file with column names that the user can understand. How can i set these new column names.My code is shown below.Thanks in advance.
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();
}
Here is a sample code what I'm using.
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();
}
You can use a simple sql query to export a mysql table to 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.