思路是:
- 創建一個查詢,查詢出你要的數據的結果集(感覺這個可以不用實體類)
- 創建一個查詢的實體類excel表,並創建工作簿,創建表內容並標註第一行說明內容。
- 從第二行開始每一行每一單元格循環填充數據內容。
- 命名錶名+日期.xls
- 使用文件輸出流輸出表。
首先,你得POI導出的jar包,我用了maven倉庫的依賴,解決導入jar包的問題。
POI使用jar包:
<!-- POI導出 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
servlet使用的jar包:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
<exclusion>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>jstl-impl</artifactId>
<version>1.2</version>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
<exclusion>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
</exclusion>
<exclusion>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
</exclusion>
</exclusions>
</dependency>
oracle連接ojdbc的jar包:
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc7</artifactId>
<version>12.1.0.1.0</version>
</dependency>
前端設置個按鈕用於控制導出操作:
index.jsp:
<%@ page language="java" import="java.util.*" contentType="charset=utf-8"
pageEncoding="utf-8" isELIgnored="false" %>
<script type="text/javascript">
function importExcel(){
window.location.href="/imandexdata/ImportMsgServlet";
window.alert("reflect!!");
}
</script>
<html>
<meta charset="utf-8">
<title>personinfo</title>
<body>
<h2>用戶信息表</h2>
<div class="aaa">
<table><tr><td>
<button id="importExl" οnclick="importExcel()">導出數據到Excel表(E盤)</button>
</td> </tr></table>
</div>
</body>
</html>
ImportMsgServlet.java:
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.ImportMsgDao;
/**
* Servlet implementation class ImportMsgServlet
*/
public class ImportMsgServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
//使用doget方法
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
ImportMsgDao imd = new ImportMsgDao();
imd.importMsg();
}
}
ImportMsgDao.java:
package dao;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import util.DbUtil;
public class ImportMsgDao {
DbUtil dbUtil=new DbUtil();
//導出一張表格
public void importMsg() {
// TODO Auto-generated constructor stub
//response.setCharacterEncoding("text/html;charset=utf-8");
Connection conn=null;
try {
conn=dbUtil.getCon();
//List<Person> pList = new ArrayList<Person>();
//從數據庫中拿數據
ResultSet rs = queryUserInfo(conn);
HSSFWorkbook workbook= defineExcel(rs);
export(workbook);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
dbUtil.closeCon(conn);
}
}
//從數據庫查詢出結果並將其
public ResultSet queryUserInfo(Connection conn) throws Exception {
String sql = "select p.personid,p.firstname,p.lastname,a.Addressid,a.city,a.state \r\n" +
"from Person p left join Address a \r\n" +
"on p.Addressid=a.addressid \r\n" +
"group by p.personid,p.firstname,p.lastname,a.Addressid,a.city,a.state\r\n" +
"order by p.personid";
StringBuffer sb = new StringBuffer(sql);
PreparedStatement pps= conn.prepareStatement(sb.toString());
ResultSet rs= pps.executeQuery();
return rs;
}
//自定義一個Excel表,並完成第一行的內容
public HSSFWorkbook defineExcel(ResultSet rs) throws Exception {
HSSFWorkbook Workbook = new HSSFWorkbook();
//創建sheet頁
HSSFSheet sheet = Workbook.createSheet("人員信息");
//第一行
int rowIndex = 0;
//創建頁的行
Row row= sheet.createRow(rowIndex++);
System.out.println("rowIndex============"+rowIndex);
//首標題每列的內容
String[] headers= {"用戶編號","姓","名","地址編號","城市","州或省"};
//首行的列創建及賦值
for(int i=0;i<headers.length;i++) {
//System.out.println("headers["+i+"]====="+headers[i]);
//給一行創建幾列並給每列添加數組的內容
row.createCell(i).setCellValue(headers[i]);
}
while(rs.next()) {
row = sheet.createRow(rowIndex++);
System.out.println("rowIndex============"+rowIndex);
for(int i = 0;i < headers.length;i++) {
row.createCell(i).setCellValue(rs.getObject(i+1).toString());
//rs.getObject(i + 1)得到一個對象,即數據庫中一行的結果,每一列就是屬性湊成一行變成對象。因爲id是從1開始,所以要+1。
}
}
return Workbook;
}
//導出表
public void export(Workbook wb) throws Exception{
SimpleDateFormat sdff = new SimpleDateFormat("yyyyMMddHHmmss");
//excel文件名稱
String filename = "人員信息導出數據" + sdff.format(new Date()) + ".xls";
FileOutputStream out = new FileOutputStream("e:\\"+filename);
wb.write(out);
//fileOut.close();
System.out.print("OK");
out.close();
out.flush();
}
}