利用POI组件 导入导出excel

项目中经常遇到要将列表中的数据导出到excel中或是要将已经存在的excel文档的数据导入到数据库中。这里记录下在struts1.2中的用法。
1、从excel导入
/**
* 从处部excel文件中导入应急物资记录
* @param mapping
* @param form
* @param request
* @param response
* @return
*/
public ActionForward importMaterials(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response){

int beginRowIndex = 2; //从excel中开始读取的起始行数
int totalRows = 0; //该excel表的总行数
IUserProfile userPro = (IUserProfile) request.getSession().getAttribute(IUserProfile.SESSION_USERPROFILE_KEY);

ImportFileForm importFileForm = (ImportFileForm)form;

//读取要导入的文件
FormFile file = importFileForm.getExcelfile();
String title = file.getFileName().replaceAll(".xls", "");
logger.debug("标题是:"+title);
try {
//根据文件的输入流,创建对Excel工作簿文件的引用
HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream());
//默认excel的书页(sheet)是"Sheet1"
HSSFSheet sheet = workbook.getSheetAt(0);
//该excel表的总行数
totalRows = sheet.getLastRowNum();
logger.debug("输出总行数:"+totalRows);

//循环读取excel表格的每行记录,并逐行进行保存
for(int i=beginRowIndex;i<=totalRows;i++){
HSSFRow row = sheet.getRow(i);
//获取一行每列的数据
HSSFCell materialNameCell = row.getCell((short)0);
HSSFCell amountCell = row.getCell((short)1);
HSSFCell orgCell = row.getCell((short)2);
HSSFCell storePlaceCell = row.getCell((short)3);
HSSFCell buyTimeCell = row.getCell((short)4);
HSSFCell periodCell = row.getCell((short)5);
HSSFCell principalNameCell = row.getCell((short)6);
HSSFCell principalMobileCell = row.getCell((short)7);
HSSFCell linkManCell = row.getCell((short)8);
HSSFCell linkManMobileCell = row.getCell((short)9);

//将列数据赋给相关变量
String materialName = materialNameCell.getRichStringCellValue().getString();
String amount = amountCell.getRichStringCellValue().getString();
String orgName = orgCell.getRichStringCellValue().getString(); String storePlace = storePlaceCell.getRichStringCellValue().getString();
String buyTime = "";
if(buyTimeCell.getCellType()==HSSFCell.CELL_TYPE_NUMERIC){
buyTime = new Double(buyTimeCell.getNumericCellValue()).toString();
}else if(buyTimeCell.getCellType()==HSSFCell.CELL_TYPE_STRING){
buyTime = buyTimeCell.getRichStringCellValue().getString();
}
String period = "";
if(periodCell.getCellType()==HSSFCell.CELL_TYPE_NUMERIC){
period = new Double(periodCell.getNumericCellValue()).toString();
}else if(periodCell.getCellType()==HSSFCell.CELL_TYPE_STRING){
period = periodCell.getRichStringCellValue().getString();
}
String principalName= principalNameCell.getRichStringCellValue().getString();
String principalMobile= new Long((long)principalMobileCell.getNumericCellValue()).toString();
String linkMan = linkManCell.getRichStringCellValue().getString();
String linkManMobile = new Long((long)linkManMobileCell.getNumericCellValue()).toString();

//保存当前行的数据
try{
saveMaterial(materialName,amount,orgName,storePlace,buyTime,period,principalName,principalMobile,linkMan,linkManMobile,userPro);

}catch(Exception e){
throw e;
}
} //for end
MessageDisplayService.disposeMessage(request, response,"导入文件成功");
} catch (FileNotFoundException e) {
MessageDisplayService.disposeMessage(request, response,"找不到文件");
} catch (IOException e) {
MessageDisplayService.disposeMessage(request, response,"导入文件失败,连接数据库失败");
} catch(Exception e){
e.printStackTrace();
MessageDisplayService.disposeMessage(request, response,"导入文件失败,文档模板格式不正确");
}
return mapping.findForward("import_ok");

}



/**
* 将从excel中抽取的一行物资记录转换后存入数据库
* @param userPro
*/
private void saveMaterial(String materialName,
String amount,
String orgName,
String storePlace,
String buyTime,
String period,
String principalName,
String principalMobile,
String linkMan,
String linkManMobile,
IUserProfile userPro) throws Exception{
MaterialForm form = new MaterialForm();
form.setMaterialName(materialName);
form.setAmount(amount);
form.setOrgName(orgName);
form.setStorePlace(storePlace);
form.setBuyTime(buyTime);
form.setPeriod(period);
form.setPrincipalName(principalName);
form.setPrincipalMobile(principalMobile);
form.setLinkman(linkMan);
form.setLinkmanMobile(linkManMobile);
//保存
materialManager.saveOrUpdate(form, userPro);
}


2、从数据库导出到excel中
/**
* 根据条件导出excel(可选择导出项)
* @param form
* @param request
* @param response
* @throws IOException
*/
public void exportStreetEvent(ActionForm form,HttpServletRequest request,HttpServletResponse response) throws IOException{


HSSFWorkbook workbook = new HSSFWorkbook();
int sheetRowNum = 0;
XwzsEventQueryForm xwzsEventQueryForm = (XwzsEventQueryForm)form;

/**从库中取出相关数据**/
List list12 = xwzsEventManager.getEventQuery(xwzsEventQueryForm,projections);
List list = getEventExport(list12); //将取出的列表格式化,不是必须

String title = "事件列表";
// 创建工作表和标题
HSSFSheet sheet = workbook.createSheet("event");
// 设置标题栏合并区域
Region r = new Region(0, (short) 0, 0, (short) 12);
ExportUtil.fillMergedRegion(workbook, sheet, r, title, workbook.createCellStyle());
sheetRowNum++;
// 设置列宽
// 默认列宽
sheet.setDefaultColumnWidth((short) 10);
// 自定义列宽
// sheet.autoSizeColumn((short)1);
sheet.setColumnWidth((short)1, (short)(268*21));
sheet.setColumnWidth((short)3, (short)(268*13));
sheet.setColumnWidth((short)10, (short)(268*21));
sheet.setColumnWidth((short)11, (short)(268*16));

// 设置字体格式
HSSFFont font = workbook.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
font.setFontName("仿宋_GB2312");
font.setFontHeightInPoints((short) 12);
// 创建格式模型
HSSFCellStyle cs = workbook.createCellStyle();
cs.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
cs.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);
cs.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
cs.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
// 自动换行
cs.setWrapText(true);
// 上下居中
cs.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
cs.setFont(font);
// 创建数据项格式
HSSFCellStyle cs1 = workbook.createCellStyle();
cs1.setBorderTop(HSSFCellStyle.BORDER_THIN);
cs1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cs1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cs1.setBorderRight(HSSFCellStyle.BORDER_THIN);
cs1.setWrapText(true);
cs1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
String[] titles = { "日期", "期号", "事发时间", "首报时间", "首报单位","地点","事件标题","类别","等级","领导现场指挥","区领导批示","报市应急办","处置中存在的问题","首报人","接电人" };
HSSFRow dataTitleRow = sheet.createRow((short) sheetRowNum++);


//获取用户选择的输出项
for (int i = 0; i < titles.length; i++) {
HSSFCell cell = dataTitleRow.createCell((short) i);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(new HSSFRichTextString(titles[i]));
cell.setCellStyle(cs);
}

// 数据模型转换:创建表格数据
for (int i = 0; i < list.size(); i++) {
EventExport eventexport = (EventExport) list.get(i);
HSSFRow dataRow = sheet.createRow((short) (i+sheetRowNum));
HSSFCell celldate = dataRow.createCell((short) 0);
HSSFCell cellqihao = dataRow.createCell((short) 1);
HSSFCell cellhappentime = dataRow.createCell((short) 2);
HSSFCell cellreporttime = dataRow.createCell((short) 3);
HSSFCell cellreportdepart = dataRow.createCell((short) 4);
HSSFCell celladdress = dataRow.createCell((short) 5);
HSSFCell cellevent = dataRow.createCell((short) 6);
HSSFCell celltype = dataRow.createCell((short) 7);
HSSFCell cellgrade = dataRow.createCell((short) 8);
HSSFCell cellcommand = dataRow.createCell((short) 9);
HSSFCell cell1denote = dataRow.createCell((short) 10);
HSSFCell cell1report = dataRow.createCell((short) 11);
HSSFCell cell1problem = dataRow.createCell((short) 12);
// 中文编码
celldate.setCellValue(new HSSFRichTextString(eventexport.getDate()));
cell2.setCellValue(new HSSFRichTextString(jinzhan.getDetailcontent()));
cellhappentime.setCellValue(new HSSFRichTextString(eventexport.getHappentime()));
cellreporttime.setCellValue(new HSSFRichTextString(eventexport.getReporttime()));
cellreportdepart.setCellValue(new HSSFRichTextString(eventexport.getDepartment()));
celladdress.setCellValue(new HSSFRichTextString(eventexport.getPlace()));
cellevent.setCellValue(new HSSFRichTextString(eventexport.getEventcontent()));
celltype.setCellValue(new HSSFRichTextString(eventexport.getEventtype()));
cellgrade.setCellValue(new HSSFRichTextString(eventexport.getEventlevel()));
cellcommand.setCellValue(new HSSFRichTextString(eventexport.getLocalleader()));
cell1denote.setCellValue(new HSSFRichTextString(eventexport.getDenote()));
cell1report.setCellValue(new HSSFRichTextString(eventexport.getReportflag()));

// 设置各个列的格式
celldate.setCellStyle(cs1);
cellqihao.setCellStyle(cs1);
cellhappentime.setCellStyle(cs1);
cellreporttime.setCellStyle(cs1);
cellreportdepart.setCellStyle(cs1);
celladdress.setCellStyle(cs1);
cellevent.setCellStyle(cs1);
celltype.setCellStyle(cs1);
cellgrade.setCellStyle(cs1);
cellcommand.setCellStyle(cs1);
cell1denote.setCellStyle(cs1);
cell1report.setCellStyle(cs1);
cell1problem.setCellStyle(cs1);

}
//输出文件
OutputStream out = response.getOutputStream();
response.setCharacterEncoding("gbk");
response.setContentType("application/x-msexcel");
response.setHeader("Content-Disposition", "attachment;filename="
+ ExportUtil.UniC(title) + ".xls");

workbook.write(out);
out.close();
}




/**
* 添加标题栏的内容和设置标题格式
*
* @param workbook
* @param sheet
* @param region
* @param text
* @param cs
*/
public static void fillMergedRegion(HSSFWorkbook workbook, HSSFSheet sheet,
Region region, String text, HSSFCellStyle cs) {
cs.setAlignment(HSSFCellStyle.ALIGN_CENTER);
setRegionStyle(workbook, sheet, region, cs);
HSSFRow row;
HSSFCell cell;
// 设置字体格式
HSSFFont font = workbook.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font.setFontHeightInPoints((short) 18);
// 居中显示
cs.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cs.setFont(font);

row = sheet.getRow(region.getRowFrom());
cell = row.getCell(region.getColumnFrom());
cell.setCellValue(new HSSFRichTextString(text));
sheet.addMergedRegion(region);
}




public static void setRegionStyle(HSSFWorkbook workbook, HSSFSheet sheet,
Region region, HSSFCellStyle cs) {
for (int i = region.getRowFrom(); i <= region.getRowTo(); i++) {
HSSFRow row = HSSFCellUtil.getRow(i, sheet);
for (int j = region.getColumnFrom(); j <= region.getColumnTo(); j++) {
HSSFCell cell = HSSFCellUtil.getCell(row, (short) j);
cell.setCellStyle(cs);
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值