推荐使用这种方式,因为封装性更好,当需要导出的表列需要变动时,只需要在js文件中改动就行了,不像使用Action方法时需要变动Action中的Java代码。
每次点击导出按钮后,调用ExportExcel函数并传入fileName、columnItemsStr、sql三个参数,该函数完成Excel文件导出至客户端的功能。传入参数时需要注意Extjs传递中文参数至后台时乱码的处理。本文中已经做了处理,具体是:在js中对中文参数作两次编码处理,如:var fileName = "光纤段"; var url = 'ExportExcel' + '?fileName=' + encodeURI(encodeURI(fileName)) + '&columnItemsStr=' + encodeURI(encodeURI(columnItemsStr)) +'&sql=' + sql;,后台接收参数时,要进行解码:String fileName = URLDecoder.decode(request.getParameter("fileName"),"UTF-8");,这样在后台就能获取到中文参数。
servlet文件内容(导出Excel文件功能的封装):
package com.otdrmsys.servlet;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.otdrmsys.util.DB;
/**
* Servlet implementation class ExportExcel
*/
public class ExportExcel extends HttpServlet {
private static final long serialVersionUID = 1L;
public static final Logger errorLogger = Logger.getLogger("dailyError");
public static final Logger infoLogger = Logger.getLogger("dailyInfo");
/**
* @see HttpServlet#HttpServlet()
*/
public ExportExcel() {
super();
}
/**
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName = URLDecoder.decode(request.getParameter("fileName"),"UTF-8");
String columnItemsStr = URLDecoder.decode(request.getParameter("columnItemsStr"),"UTF-8");
String sql = request.getParameter("sql");
String[] columnItems = columnItemsStr.split(",");//从字符串形式的列名中获取列名数组
Connection conn = DB.createConn();
PreparedStatement ps = DB.prepare(conn, sql);
ResultSet rs = null;
try {
rs = ps.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
HSSFWorkbook workbook = new HSSFWorkbook();
try {
HSSFSheet sheet = workbook.createSheet();
createTag(columnItems, sheet);// 写表格的列名
createValue(rs, sheet);// 获取数据集,然后获得数据,写文件
//通过Response把数据以Excel格式保存
response.reset();
response.setContentType("application/msexcel;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=\""
+ new String((fileName + ".xls").getBytes("GBK"),"ISO8859_1") + "\"");
OutputStream outputStream = response.getOutputStream();
workbook.write(outputStream); //输出文件到客户端
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
DB.close(ps);
DB.close(conn);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* 创建表格表头
*
* @param tags
* @param sheet
*/
private static void createTag(String[] tags, HSSFSheet sheet) {
HSSFRow row = sheet.createRow(0);
HSSFCell cell = null;
// 定义单元格为字符串类型
for (int i = 0; i < tags.length; i++) {
cell = row.createCell(i);
cell.setCellValue(tags[i]);
// cell.setCellType(HSSFCell.ENCODING_UTF_16);// 中文处理
}
}
/**
* 设置表格内容
*
* @param res
* @param sheet
*/
private static void createValue(java.sql.ResultSet res, HSSFSheet sheet) {
try {
int flag = 1;
int count = res.getMetaData().getColumnCount();
HSSFRow row = null;
HSSFCell cell = null;
while (res.next()) {
row = sheet.createRow(flag);
for (int i = 1; i <= count; i++) {
cell = row.createCell(i - 1);
Object obj = res.getObject(i);
cell.setCellValue(obj + "");
}
flag++;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
package com.otdrmsys.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DB {
public static Connection createConn() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/wenling_map_db", "root", "hel610");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static PreparedStatement prepare(Connection conn, String sql) {
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return ps;
}
public static void close(Connection conn) {
try {
conn.close();
conn = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(Statement stmt) {
try {
stmt.close();
stmt = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(ResultSet rs) {
try {
rs.close();
rs = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
{
id: 'fiberLineBackupBtnId',
text: '导出',
hidden: true,
tooltip: '备份光纤段信息',
iconCls: 'save',
handler: function(){
var fileName = "光纤段";// 文件名,不带路径,不带.xls后缀
var columnItemsStr = "光纤段id,光纤段名称,起点,终点,负责人,负责人手机号";
var sql = "select id, name,( "
+ "select name from _station s where s.id = f.startPoint_id ),( "
+ "select name from _station s where s.id = f.endPoint_id ),( "
+ "select name from _repairer r where r.id = f.repairer_id ), ( "
+ "select phoneNum from _repairer r where r.id = f.repairer_id ) "
+ "from _fiberline f;";
var url = 'ExportExcel' + '?fileName=' + encodeURI(encodeURI(fileName)) + '&columnItemsStr=' + encodeURI(encodeURI(columnItemsStr)) +'&sql=' + sql;
window.location.href = url ;
}
}
下载后的文件内容: