1. 程式人生 > >POI操作Excell表,匯入,匯出

POI操作Excell表,匯入,匯出

POI操作Excell表

1,匯入jar包
POI所需要的jar包
2,jsp頁面 ,使用了一鍵上傳的外掛
一鍵上傳外掛

  • 匯出資料 請選擇 匯出當前頁資料 匯出全部資料
匯入Excel //匯入資料 $(function () { $("#button-import").upload({ action:"${ctx}/workOrderController/importExcel", name: 'myFile', onComplete: function(data) { if(data == '1'){ //上傳成功 /* $.messager.alert("提示資訊","區域資料匯入成功!","info"); alert(1);*/ alert("上傳成功"); $("#recieveListFrom").load("${ctx}/workOrderController/toRecieveList"); }else{ alert("上傳失敗"); /* //失敗 $.messager.alert("提示資訊","區域資料匯入失敗!","warning");*/ } }
    });
})
/**
 * 將數匯出到excel表格
 */
function exportExcel() {
    var exportExcels= $("#exportExcel").val();
    //alert(exportExcel);
    if(exportExcels!=''&& exportExcels !=null && exportExcels!='null'){
    location.href = "${ctx}/workOrderController/exportExcel?exportExcels="+exportExcels;
    }
}

3,Controller層,將Excell表中的資料匯入並儲存到資料庫
@RequestMapping(value="/importExcel")
@ResponseBody
public String importExcel(HttpServletRequest request, HttpServletResponse response)throws Exception{
String flag=“1”;
MultipartHttpServletRequest multipartRequest= (MultipartHttpServletRequest) request;
MultipartFile myFile = multipartRequest.getFile(“myFile”);//// 通過引數名獲取指定檔案 檔案本身 變數名和檔案上傳時的 名稱保持一致
String myFileName = myFile.getOriginalFilename();//檔案的名字
List list = workOrderService.importExcel(myFile,request,response,myFileName);
if(list.isEmpty()){
flag=“0”;
}
//批量儲存
workOrderService.batchAdd(list);
response.setContentType(“text/html;charset=UTF-8”);
response.getWriter().print(flag);
return null;
}
4,Service層,匯入的主要業務邏輯
public List importExcel(MultipartFile myFile, HttpServletRequest request, HttpServletResponse response,String myFileName){
List list = new ArrayList();
Workbook workbook=null;
String fileType=myFileName.substring(myFileName.lastIndexOf("."));
//使用POI解析Excel檔案
try {
InputStream in = myFile.getInputStream();
if(".xls".equals(fileType)){
workbook=new HSSFWorkbook(in);
}
if(".xlsx".equals(fileType)){
workbook=new XSSFWorkbook(in);
}
//獲得第一個sheet頁
Sheet sheet = null;
for(int j=0;j<workbook.getNumberOfSheets();j++){
sheet=workbook.getSheetAt(j);
for (Row row : sheet) {
int rowNum = row.getRowNum();
if (rowNum == 0) {
//第一行,標題行,忽略
continue;
}
List communityList = findAllCommunity(TableRoute.getUserCode());
String communityName = ExcelUtil.getCellValue(row.getCell(0));
String communityCode = “”;
if (null != communityList && communityList.size() > 0) {
int size = communityList.size();
for (int i = 0; i < size; i++) {
Community community = communityList.get(i);
String name = community.getCommunityName();
if (name.equals(communityName)) {
communityCode = community.getId();
break;
}
}
}
//來電人
String phoneMan =ExcelUtil.getCellValue(row.getCell(1));
//來電人號碼
String phoneNum=ExcelUtil.getCellValue(row.getCell(2));
//地址
String address =ExcelUtil.getCellValue(row.getCell(3));
//問題分類
String problemName =ExcelUtil.getCellValue(row.getCell(4));
//工單,描述
String description =ExcelUtil.getCellValue(row.getCell(5));
//工單編號
String recieveNum =ExcelUtil.getCellValue(row.getCell(6));
//地圖定位ID
String caseObjectId=ExcelUtil.getCellValue(row.getCell(7));
Recieve recieve = new Recieve();
recieve.setCommunityCode(communityCode);
recieve.setPhoneMan(phoneMan);
recieve.setPhoneNum(phoneNum);
recieve.setAddress(address);
recieve.setProblemName(problemName);
recieve.setDescription(description);
recieve.setRecieveNum(recieveNum);
recieve.setCaseObjectId(caseObjectId);
recieve.setIsDelete(0);
;//設定日期格式
SimpleDateFormat df = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
String createTime = df.format(new Date());
recieve.setCreateTime(createTime);
recieve.setUpdateTime("");
list.add(recieve);
}
}
}
catch (IOException e) {
e.printStackTrace();
}
return list;
}
將資料庫中的資料匯出到Excell表


1,Controller
@RequestMapping(value = “exportExcel”)
public void exportExcel(HttpServletRequest request,HttpServletResponse response){
SimpleDateFormat df = new SimpleDateFormat(“yyyy-MM-dd-HH-mm-ss”);
String datatime = df.format(new Date());
String exportExcels=request.getParameter(“exportExcels”);
String filename = “花鄉資料”+datatime+".xlsx";
String agent = request.getHeader(“User-Agent”);
filename = FileUtils.encodeDownloadFilename(filename, agent);
//一個流兩個頭
try {
ServletOutputStream outputStream = response.getOutputStream();
String contentType = request.getServletContext().getMimeType(filename);
response.setContentType(contentType);
response.setHeader(“content-disposition”, “attchment;filename=”+filename);
workOrderService.exportExcel(outputStream,request,exportExcels);
} catch (IOException e) {
e.printStackTrace();
}
}
2,service
public void exportExcel(ServletOutputStream outputStream,HttpServletRequest request,String exportExcels){
Map<String, Object> map=(Map<String, Object>)request.getSession().getAttribute(“mapSession”);
List list=null;
XSSFSheet sheet=null;
XSSFWorkbook workbook= new XSSFWorkbook();
//匯出當前頁的資料
if(exportExcels.equals(“currentPage”)){
list=recieveMapper.selectRecieveList(map);
sheet=workbook.createSheet(“花鄉匯出資料”);
sheet.setDefaultColumnWidth((short)20);
// 建立標題行
XSSFRow headRow = sheet.createRow(0);
headRow.createCell(0).setCellValue(“屬地”);
headRow.createCell(1).setCellValue(“來電人姓名”);
headRow.createCell(2).setCellValue(“來電人號碼”);
headRow.createCell(3).setCellValue(“地址”);
headRow.createCell(4).setCellValue(“問題分類”);
headRow.createCell(5).setCellValue(“工單描述”);
headRow.createCell(6).setCellValue(“工單編號”);
headRow.createCell(7).setCellValue(“地圖定位id”);
headRow.createCell(8).setCellValue(“工單創鍵時間”);
headRow.createCell(9).setCellValue(“修改工單時間”);
for (Recieve recieve: list) {
//從第二行開始,去掉標題行
Row dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
//屬地 通過code查詢name值
String communityCode=recieve.getCommunityCode();
String communityName=communityMapper.findCommunityNameByCode(communityCode);
dataRow.createCell(0).setCellValue(communityName);
//來電人
dataRow.createCell(1).setCellValue(recieve.getPhoneMan());
//來電號碼
dataRow.createCell(2).setCellValue(recieve.getPhoneNum());
//地址
dataRow.createCell(3).setCellValue(recieve.getAddress());
//問題分類
dataRow.createCell(4).setCellValue(recieve.getProblemName());
//工單描述
dataRow.createCell(5).setCellValue(recieve.getDescription());
//工單編號
dataRow.createCell(6).setCellValue(recieve.getRecieveNum());
//地圖定位id
dataRow.createCell(7).setCellValue(recieve.getCaseObjectId());
//工單建立時間
dataRow.createCell(8).setCellValue(recieve.getCreateTime());
//工單修改時間
dataRow.createCell(9).setCellValue(recieve.getUpdateTime());
}
}
//匯出全部的資料 分為全部匯出,和匯出當前頁
else if(exportExcels.equals(“All”)){
//list=recieveMapper.findRecieveList
(map);
int count = recieveMapper.selectRecieveCount(map);
int size=count/10+1;
for(int i=1;i<=size;i++){
page.setPageNo(i);
map.put(“page”, page);
list=recieveMapper.selectRecieveList(map);
sheet=workbook.createSheet(“花鄉匯出資料”+i);
sheet.setDefaultColumnWidth((short)20);
// 建立標題行
XSSFRow headRow = sheet.createRow(0);
headRow.createCell(0).setCellValue(“屬地”);
headRow.createCell(1).setCellValue(“來電人姓名”);
headRow.createCell(2).setCellValue(“來電人號碼”);
headRow.createCell(3).setCellValue(“地址”);
headRow.createCell(4).setCellValue(“問題分類”);
headRow.createCell(5).setCellValue(“工單描述”);
headRow.createCell(6).setCellValue(“工單編號”);
headRow.createCell(7).setCellValue(“地圖定位id”);
headRow.createCell(8).setCellValue(“工單創鍵時間”);
headRow.createCell(9).setCellValue(“修改工單時間”);
for (Recieve recieve: list) {
//從第二行開始,去掉標題行
Row dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
//屬地 通過code查詢name值
String communityCode=recieve.getCommunityCode();
String communityName=communityMapper.findCommunityNameByCode(communityCode);
dataRow.createCell(0).setCellValue(communityName);
//來電人
dataRow.createCell(1).setCellValue(recieve.getPhoneMan());
//來電號碼
dataRow.createCell(2).setCellValue(recieve.getPhoneNum());
//地址
dataRow.createCell(3).setCellValue(recieve.getAddress());
//問題分類
dataRow.createCell(4).setCellValue(recieve.getProblemName());
//工單描述
dataRow.createCell(5).setCellValue(recieve.getDescription());
//工單編號
dataRow.createCell(6).setCellValue(recieve.getRecieveNum());
//地圖定位id
dataRow.createCell(7).setCellValue(recieve.getCaseObjectId());
//工單建立時間
dataRow.createCell(8).setCellValue(recieve.getCreateTime());
//工單修改時間
dataRow.createCell(9).setCellValue(recieve.getUpdateTime());
}
}
}

    try {
        //將資料寫入
        workbook.write(outputStream);
    } catch (IOException e) {
        e.printStackTrace();
    }

}
3,Mapper  分頁
<!-- 查詢列表 -->
<select id="selectRecieveList" parameterType="Map" resultMap="BaseResultMap">
    select
    <include refid="select_column_list" />
    from t_h_recieve t
    where t.isDelete = 0
    <if test="recieve.communityCode != null and recieve.communityCode != '' and recieve.communityCode !='null'">
        AND
        t.communityCode = #{recieve.communityCode}
    </if>
    <if test="recieve.recieveNum != null and recieve.recieveNum != ''">
        AND
        t.recieveNum  like  CONCAT(CONCAT('%',#{recieve.recieveNum},'%'))
    </if>
    <if test="recieve.phoneMan != null and recieve.phoneMan != ''">
        AND
        t.phoneMan like CONCAT(CONCAT('%',#{recieve.phoneMan},'%'))
    </if>
    <if test="recieve.phoneNum != null and recieve.phoneNum != ''">
        AND
        t.phoneNum like CONCAT(CONCAT('%',#{recieve.phoneNum},'%'))
    </if>
    <if test="recieve.problemName != null and recieve.problemName !=''">
        AND
        t.problemName=#{recieve.problemName}
    </if>
    <if test="recieve.monthCategory !=null and recieve.monthCategory !='' and recieve.monthCategory !='null' ">
        AND
        t.createTime like CONCAT(CONCAT(LEFT(t.createTime,5),#{recieve.monthCategory},'%'))
    </if>
    order by id desc
	<include refid="Oracle_Dialect_Suffix"></include>
</select>
4,展示效果

在這裡插入圖片描述