<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.11</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.11</version>
</dependency>
package com.itcast.poi;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
publicclassTest4{
staticSimpleDateFormat sdf =newSimpleDateFormat("yyyy-MM-dd HH:mm:ss");
publicstaticvoid main(String[] args){
// 创建一个excel文档,在这个excel文档中写入一句话,把excel文档输出到D盘
HSSFWorkbook book =newHSSFWorkbook();//工作薄
HSSFSheet sheet = book.createSheet();//工作表
// 设置单元格样式
HSSFCellStyle cellStyle = book.createCellStyle();
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
// 水平居中对齐
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 垂直居中对齐
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 设置字体
HSSFFont font = book.createFont();
// 黑体18号并且加粗
font.setFontName("黑体");//字体名称
font.setFontHeightInPoints((short)18);//字号大小
font.setBold(true);//加粗
// 把字体放到样式中
cellStyle.setFont(font);
// 15行4列
for(int i =0; i <15; i++){
HSSFRow row = sheet.createRow(i);
/**
* 设置行高
*/
row.setHeight((short)500);
for(int j =0; j <4; j++){
HSSFCell cell = row.createCell(j);
cell.setCellStyle(cellStyle);
}
}
// 设置列宽
for(int i =0; i <4; i++){
sheet.setColumnWidth(i,5000);
}
// 合并单元格 firstRow 起始行, lastRow 截止行, firstCol 起始列, lastCol截止列
sheet.addMergedRegion(newCellRangeAddress(1,1,0,3));
// 向合并单元格中放一个当前时间
HSSFCell cell = sheet.getRow(1).getCell(0);
String dateStr = sdf.format(newDate());
cell.setCellValue(dateStr);
// 设置单元格样式
HSSFCellStyle cellStyle1 = book.createCellStyle();
cellStyle1.cloneStyleFrom(cellStyle);
// 设置字体
HSSFFont font1 = book.createFont();
// 黑体18号并且加粗
font1.setFontName("楷体");//字体名称
font1.setFontHeightInPoints((short)11);//字号大小
// font1.setBold(false);//加粗
// 把字体放到样式中
cellStyle1.setFont(font1);
HSSFCell contentCell = sheet.getRow(2).getCell(0);
contentCell.setCellStyle(cellStyle1);
contentCell.setCellValue("第一组");
try{
book.write(newFileOutputStream("d:\\demo3.xls"));
}catch(FileNotFoundException e){
// TODO Auto-generated catch block
e.printStackTrace();
}catch(IOException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
response.setHeader("Content-Disposition","attachment;fileName="+newString(fileName.getBytes("utf-8"),"iso-8859-1"));
iconCls:'icon-save',
text:'导出',
handler:function(){
// alert(123);
// window.open("dep.html");
var formdata=$("#searchForm").serializeJSON();
formdata['t1.type']=Request['type'];
$.download("supplier_export.action",formdata);
}
/**
* 导出--是一个excel文件
* @param t1
* @throws UnsupportedEncodingException
*/
publicvoid export()throwsUnsupportedEncodingException{
HttpServletResponse response =ServletActionContext.getResponse();
String fileName ="供应商.xls";
Supplier t1 = getT1();
if(t1.getType().equals("2")){
fileName="客户.xls";
}
response.setHeader("Content-Disposition","attachment;fileName="+newString(fileName.getBytes(),"iso-8859-1"));
ServletOutputStream out;
try{
out = response.getOutputStream();
supplierBiz.export(t1, out);
}catch(IOException e){
e.printStackTrace();
}
}
publicvoid export(Supplier t1 ,OutputStream out){
// 创建excel文档(工作薄)
HSSFWorkbook book =newHSSFWorkbook();
String sheetname="供应商";
if(t1.getType().equals("2")){
sheetname="客户";
}
HSSFSheet sheet = book.createSheet(sheetname);
HSSFRow titleRow = sheet.createRow(0);
HSSFCell cell =null;
cell = titleRow.createCell(0);
cell.setCellValue("名称");
cell = titleRow.createCell(1);
cell.setCellValue("地址");
cell = titleRow.createCell(2);
cell.setCellValue("联系人");
cell = titleRow.createCell(3);
cell.setCellValue("电话");
cell = titleRow.createCell(4);
cell.setCellValue("email");
List<Supplier> list = supplierDao.getList(t1,null,null);
int rowIndex =1;
for(Supplier supplier : list){
HSSFRow row = sheet.createRow(rowIndex);
cell = row.createCell(0);//名称
cell.setCellValue(supplier.getName());
cell = row.createCell(1);//地址
cell.setCellValue(supplier.getAddress());
cell = row.createCell(2);//联系人
cell.setCellValue(supplier.getContact());
cell = row.createCell(3);//电话
cell.setCellValue(supplier.getTele());
cell = row.createCell(4);//email
cell.setCellValue(supplier.getEmail());
rowIndex++;
}
try{
book.write(out);
book.close();
}catch(IOException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
}
publicvoid export()throwsIOException{
HttpServletResponse response =ServletActionContext.getResponse();
response.setHeader("content-disposition","attachment;fileName=orders.xls");
ServletOutputStream out = response.getOutputStream();
String filePath=ServletActionContext.getServletContext().getRealPath(File.separator+"template"+File.separator+"orders.xls");
FileInputStream in =newFileInputStream(filePath);
ordersBiz.export(getId(), in, out);
}
publicvoid export(Long id ,InputStream in ,OutputStream out )throwsIOException{
Orders orders = ordersDao.get(id);
HSSFWorkbook book =newHSSFWorkbook(in);
HSSFSheet sheet = book.getSheetAt(0);
Supplier supplier = supplierDao.get(orders.getSupplieruuid());
sheet.getRow(2).getCell(1).setCellValue(supplier.getName());
sheet.getRow(2).getCell(1).setCellValue(sdf.format(orders.getCreatetime()));
sheet.getRow(3).getCell(3).setCellValue(empDao.get(orders.getCreater()).getName());
if(orders.getChecktime()!=null){
sheet.getRow(4).getCell(1).setCellValue(sdf.format(orders.getChecktime()));
sheet.getRow(5).getCell(3).setCellValue(empDao.get(orders.getChecker()).getName());
}
if(orders.getStarttime()!=null){
sheet.getRow(5).getCell(1).setCellValue(sdf.format(orders.getStarttime()));
sheet.getRow(5).getCell(3).setCellValue(empDao.get(orders.getStarter()).getName());
}
if(orders.getEndtime()!=null){
sheet.getRow(6).getCell(1).setCellValue(sdf.format(orders.getEndtime()));
sheet.getRow(6).getCell(3).setCellValue(empDao.get(orders.getEnder()).getName());
}
List<Orderdetail> orderdetails = orders.getOrderdetails();
int rowIndex=9;
HSSFCell cell =null;
HSSFCellStyle cellStyle = sheet.getRow(2).getCell(0).getCellStyle();
for(Orderdetail orderdetail :orderdetails){
HSSFRow row = sheet.createRow(rowIndex);
cell = row.createCell(0);//商品名称
cell.setCellValue(orderdetail.getGoodsname());
cell.setCellStyle(cellStyle);
cell=row.createCell(1);//商品价格
cell.setCellValue(orderdetail.getPrice());
cell.setCellStyle(cellStyle);
cell=row.createCell(2);//商品数量
cell.setCellValue(orderdetail.getNum());
cell.setCellStyle(cellStyle);
cell=row.createCell(3);//金额
cell.setCellValue(orderdetail.getMoney());
cell.setCellStyle(cellStyle);
rowIndex++;
}
book.write(out);
}
POI模板导出
如果在工作中导出的单元格非常复杂时,设置样式、字体、合并单元格等代码量比较大,所以这时我们可以把即将导出的表格提前把样式、字体等都设置好,直接当做导出模板应用就可以了。
1、 提前做好excel模板,放到项目中
2、 模板拷贝到项目中
3、 BIZ中的了逻辑实现
/** * 订单的导出 * @param in * @param out * @param id * @throws IOException */ public void export(InputStream in,OutputStream out,Long id) throws IOException{ //现在的工作薄对象就是项目中的那份模板文件,所有样式都已存在,直接用就可以 HSSFWorkbook book = new HSSFWorkbook(in); HSSFSheet sheet = book.getSheetAt(0); Orders orders = ordersDao.get(id); /** * 以下就是找到相应数据所对应的单元格位置 赋值即可 */ //供应商 sheet.getRow(2).getCell(1).setCellValue(supplierDao.get(orders.getSupplieruuid()).getName()); //下单时间 String createtime = orders.getCreatetime()==null?"":sdf.format(orders.getCreatetime()); sheet.getRow(3).getCell(1).setCellValue(createtime); //审核时间 String checktime = orders.getChecktime()==null?"":sdf.format(orders.getChecktime()); sheet.getRow(4).getCell(1).setCellValue(checktime); //确认时间 String starttime = orders.getStarttime()==null?"":sdf.format(orders.getStarttime()); sheet.getRow(5).getCell(1).setCellValue(starttime); //入库时间 String endtime = orders.getEndtime()==null?"":sdf.format(orders.getEndtime()); sheet.getRow(6).getCell(1).setCellValue(endtime); //下单员 if(orders.getCreater()!=null){ sheet.getRow(3).getCell(3).setCellValue(empDao.get(orders.getCreater()).getName()); } //审核员 if(orders.getChecker()!=null){ sheet.getRow(4).getCell(3).setCellValue(empDao.get(orders.getChecker()).getName()); } //确认人 if(orders.getStarter()!=null){ sheet.getRow(5).getCell(3).setCellValue(empDao.get(orders.getStarter()).getName()); } //库管员 if(orders.getEnder()!=null){ sheet.getRow(6).getCell(3).setCellValue(empDao.get(orders.getEnder()).getName()); } //商品名称价格数量金额 List<Orderdetail> orderdetails = orders.getOrderdetails(); //取现有的样式(因为订单项所在的表格没有样式,可以从其他位置复制一份样式过来) HSSFCellStyle cellStyle = sheet.getRow(8).getCell(0).getCellStyle(); int rownum=9; //从模板中能看出来 起始行是9 for (int i = 0; i < orderdetails.size(); i++) { HSSFRow createRow = sheet.createRow(rownum+i); createRow.createCell(0).setCellStyle(cellStyle); // 设置复制过来的样式 createRow.getCell(0).setCellValue(orderdetails.get(i).getGoodsname()); createRow.createCell(1).setCellStyle(cellStyle); createRow.getCell(1).setCellValue(orderdetails.get(i).getPrice()); createRow.createCell(2).setCellStyle(cellStyle); createRow.getCell(2).setCellValue(orderdetails.get(i).getNum()); createRow.createCell(3).setCellStyle(cellStyle); createRow.getCell(3).setCellValue(orderdetails.get(i).getMoney()); } book.write(out); book.close(); } |
4、 action中获取模板文件
/** * 订单信息导出 * @throws IOException */ public void export() throws IOException{ //从项目中获取模板所在路径 File.separator 在window系统下:\ linux系统下: / String filepath=ServletActionContext.getServletContext().getRealPath(File.separator) +"template"+File.separator+"orders.xls"; HttpServletResponse response = ServletActionContext.getResponse(); //设置头部信息 response.setHeader("Content-Disposition", "attachment;fileName=orders.xls"); ServletOutputStream out = response.getOutputStream(); ordersBiz.export(new FileInputStream(filepath), out, getId()); } |
//导入
$('#importBtn').bind('click',function(){
$.ajax({
url:'supplier_doImport.action',
type:'post',
data:newFormData($("#importForm")[0]),
dataType:'json',
processData:false,
contentType:false,
success:function(data){
if(data.success){
$("#importWindow").window('close');
$("#grid").datagrid("reload");
}
$.messager.alert('提示',data.message);
}
})
});
privateFile file;
privateString fileFileName;
privateString fileContentType;
//set\get方法在上面
publicvoid doImport(){
// 获取上传的文件 file
try{
FileInputStream in =newFileInputStream(file);
supplierBiz.doImport(in);
write(ajaxReturn(true,"导入成功"));
}catch(Exception e){
write(ajaxReturn(false,"导入失败"));
e.printStackTrace();
}
0
}
/**
* 导入
* @param in
* @throws IOException
*/
publicvoid doImport(FileInputStream in)throwsIOException{
HSSFWorkbook book =newHSSFWorkbook(in);
HSSFSheet sheet = book.getSheetAt(0);
String sheetName = sheet.getSheetName();
String type="1";
if(sheetName.equals("客户")){
type="2";
}
int lastRowNum = sheet.getLastRowNum();
for(int i =1; i <= lastRowNum; i++){
Supplier supplier =newSupplier();
HSSFRow row = sheet.getRow(i);
String name = row.getCell(0).getStringCellValue();
supplier.setName(name);
List<Supplier> list = supplierDao.getList(supplier,null,null);
if(list!=null&&list.size()>0){
supplier = list.get(0);
}
String address = row.getCell(1).getStringCellValue();
supplier.setAddress(address);
String contact = row.getCell(2).getStringCellValue();
supplier.setContact(contact);
String tele = row.getCell(3).getStringCellValue();
supplier.setTele(tele);
String email = row.getCell(4).getStringCellValue();
supplier.setEmail(email);
supplier.setType(type);
if(list==null||list.size()==0){//判断是否通过name找到数据,如果没有找到数据,需要保存,如果找到数据的不需要执行add方法
supplierDao.add(supplier);
}
}
}