jar包
org.apache.poi
poi
3.15
org.apache.poi
poi-ooxml
3.15
Java代码(1):
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.TreeMap;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
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 com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mysql.MysqlParams;
import com.mysql.MysqlUtil;
import com.util.DateUtil;
import com.util.SessionContext;
import com.util.SortMapByKey;
import com.util.exportUtils;
/导出站点excel
@GetMapping(value = "/sitepoi")
public String sitepoi(HttpServletResponse response, ServletRequest request) throws Exception {
MysqlParams mysqlParams = new MysqlParams();
MysqlUtil mysqlUtil = new MysqlUtil();
Map where = new HashMap<>();
if (!StringUtils.isEmpty(request.getParameter("pid"))) {
where.put("pid", request.getParameter("pid"));
}
if (!StringUtils.isEmpty(request.getParameter("cid"))) {
where.put("cid", request.getParameter("cid"));
}
if (!StringUtils.isEmpty(request.getParameter("province"))) {
where.put("province", request.getParameter("province"));
}
if (!StringUtils.isEmpty(request.getParameter("city"))) {
where.put("city", request.getParameter("city"));
}
if (!StringUtils.isEmpty(request.getParameter("county"))) {
where.put("county", request.getParameter("county"));
}
if (!StringUtils.isEmpty(request.getParameter("contacts"))) {
where.put("contacts", request.getParameter("contacts"));
}
where.put("isdel", 0);
mysqlParams.setWhere(where);
// 分页处理
Integer page = !StringUtils.isEmpty(request.getParameter("page"))
? new Integer(request.getParameter("page")) - 1
: 0;
page = page < 0 ? 0 : page;
Integer offset = !StringUtils.isEmpty(request.getParameter("offset"))
? new Integer(request.getParameter("offset"))
: 10;
offset = Math.min(Math.max(offset, 1), 100);
mysqlParams.setLimit(page * offset, offset);
List
工具类:
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/**
* excel 导出
* @author 晓宇码匠
*
*/
public class exportUtils {
//生成excel文件
public static void buildExcelFile(String fileName,HSSFWorkbook workbook) throws Exception{
FileOutputStream fos = new FileOutputStream(fileName);
workbook.write(fos);
fos.flush();
fos.close();
}
//浏览器下载excel
public static void buildExcelDocument(String fileName, HSSFWorkbook workbook, HttpServletResponse response) throws Exception{
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "utf-8")+".xls");
OutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
}
}
java(2):
public String export(Map<?, ?> params, HttpServletResponse response) throws Exception {
Map<String, Object> respons = new HashMap<String, Object>();
MysqlParams mysqlParams = new MysqlParams();
MysqlUtil mysqlUtil = new MysqlUtil();
Map<String, Object> whereLikeMap = new HashMap<>();
Map<String, Object> where = new HashMap<>();
if (params.containsKey("pid")) {
where.put("pid", params.get("pid").toString());
}
if (params.containsKey("cid")) {
where.put("cid", params.get("cid").toString());
}
if (params.containsKey("province")) {
where.put("province", params.get("province").toString());
}
if (params.containsKey("city")) {
where.put("city", params.get("city").toString());
}
if (params.containsKey("county")) {
where.put("county", params.get("county").toString());
}
if (params.containsKey("contacts")) {
where.put("contacts", params.get("contacts").toString());
}
if (params.containsKey("address")) {
whereLikeMap.put("address", params.get("address").toString());
}
String ord = "dateline desc" ;
if (params.containsKey("ord")) {
ord = StringEscapeUtils.escapeHtml((String) params.get("ord"));
}
mysqlParams.setOrder(ord);
mysqlParams.setWhereLike(whereLikeMap);
mysqlParams.setWhere(where);
// 分页处理
Integer totals = mysqlUtil.totals("site", mysqlParams);
System.out.println(totals);
if(totals>=10000) {
respons.put("error", true);
respons.put("msg", "Data exceed 10 000 ,Please enter restrictions");
return JSON.toJSONString(respons, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero,
SerializerFeature.WriteNullBooleanAsFalse);
}
// 分页处理
mysqlParams.setLimit(0, 10000);
List<Map<String, Object>> lists = mysqlUtil.lists("site", mysqlParams);
// 数据转换
MysqlParams MysqlParams = new MysqlParams();
Map<String, Object> ParamMap = new HashMap<>();
Map<String, Object> Detail = null;
List<Map<String, String>> dataList = new ArrayList<Map<String, String>>();
for (int i = 0; i < lists.size(); i++) {
Map<String, Object> data = lists.get(i);
System.out.println(data);
Map<String, String> map = new HashMap<>();
// Customer Name 根据客户id 获取工厂名称 并放入excel
ParamMap.put("id", data.get("cid").toString());
MysqlParams.setWhere(ParamMap);
Detail = mysqlUtil.detail("customer", MysqlParams);
System.out.println(Detail.get("title").toString());
map.put("customertitle", Detail.get("title").toString());
// 清空对象
ParamMap.clear();
Detail.clear();
// Area 省区域
map.put("plantname", data.get("county").toString());
// Area 市区域
map.put("cityname", data.get("city").toString());
// Area 县区域
map.put("countyname", data.get("county").toString());
// Address 地址
map.put("address", data.get("address").toString());
// PostCode 邮政编码
map.put("postalcode", data.get("postalcode").toString());
// Product 产品名称
ParamMap.put("id", data.get("pid").toString());
MysqlParams.setWhere(ParamMap);
Detail = mysqlUtil.detail("product", MysqlParams);
System.out.println(Detail.get("title").toString());
map.put("producttitle", Detail.get("title").toString());
// 清空对象
ParamMap.clear();
Detail.clear();
// Contacts 联系人
map.put("Contacts", data.get("contacts").toString());
// Mobile 手机号
map.put("Moble", data.get("mobile").toString());
// Fixedline 座机
map.put("Fixedline", data.get("tel").toString());
dataList.add(map);
}
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("firstSheet");
// 创建表头
HSSFRow row = sheet.createRow(0);
// 设置列宽,setColumnWidth的第二个参数要乘以256,这个参数的单位是1/256个字符宽度
sheet.setColumnWidth(0, 12 * 256);
sheet.setColumnWidth(1, 32 * 256);
// 表头加粗
HSSFCellStyle style = workbook.createCellStyle();
HSSFFont font = workbook.createFont();
font.setBold(true);
style.setFont(font);
row.setRowStyle(style);
HSSFCell cell;
cell = row.createCell(0);
cell.setCellValue("id");
cell = row.createCell(1);
cell.setCellValue("Customer Name");
cell = row.createCell(2);
cell.setCellValue("Area");
cell = row.createCell(3);
cell.setCellValue("Address");
cell = row.createCell(4);
cell.setCellValue("PostCode");
cell = row.createCell(5);
cell.setCellValue("Product");
cell = row.createCell(6);
cell.setCellValue("Contacts");
cell = row.createCell(7);
cell.setCellValue("Mobile");
cell = row.createCell(8);
cell.setCellValue("Fixedline");
// 设置日期格式
HSSFCellStyle style1 = workbook.createCellStyle();
style1.setDataFormat(HSSFDataFormat.getBuiltinFormat("yyyy-MM-dd HH:mm:ss"));
// 新增数据行,并且设置单元格数据
int rowNum = 1;
String fileName = "SiteExcel";
for (int i = 0; i < dataList.size(); i++) {
row = sheet.createRow(rowNum + i);
row.createCell(0).setCellValue(i + 1);
row.createCell(1).setCellValue(dataList.get(i).get("customertitle"));
row.createCell(2).setCellValue(dataList.get(i).get("plantname")+dataList.get(i).get("cityname")+dataList.get(i).get("countyname"));
row.createCell(3).setCellValue(dataList.get(i).get("address"));
row.createCell(4).setCellValue(dataList.get(i).get("postalcode"));
row.createCell(5).setCellValue(dataList.get(i).get("producttitle"));
row.createCell(6).setCellValue(dataList.get(i).get("Contacts"));
row.createCell(7).setCellValue(dataList.get(i).get("Moble"));
row.createCell(8).setCellValue(dataList.get(i).get("Fixedline"));
}
// 生成Excel
FileOutputStream fos = new FileOutputStream(fileName);
workbook.write(fos);
fos.flush();
fos.close();
// 通知浏览器下载
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "utf-8")+".xls");
OutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
respons.put("error", false);
respons.put("msg", "Export success");
return JSON.toJSONString(respons, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero,
SerializerFeature.WriteNullBooleanAsFalse);
}
@SuppressWarnings("resource")
public String export(Map, ?> params, HttpServletResponse response) throws Exception {
Map respons = new HashMap();
String filePath = new File("").getCanonicalPath();//获取当前项目路径
String srcFilePath = filePath+"\\excel\\工资.xlsx";
System.out.println(srcFilePath);
String fileName = "工资模板";
//创建Excel文件的输入流对象
FileInputStream fis = new FileInputStream(srcFilePath);
//根据模板创建excel工作簿
XSSFWorkbook workBook = new XSSFWorkbook(fis);
//创建Excel文件输出流对象
//获取创建的工作簿第一页
XSSFSheet sheet = workBook.getSheetAt(0);
//给指定的sheet命名
workBook.setSheetName(0,"工资");
//修改标题
XSSFRow row = sheet.getRow(0);
XSSFCell cell = row.getCell(0);
//获取指定单元格值
String s = cell.getStringCellValue();
cell.setCellValue("修改后的标题为:"+s);
// 新增数据行,并且设置单元格数据
int rowNum = 1;
for (int i = 20; i <21; i++) {
row = sheet.createRow(rowNum + i);
row.createCell(0).setCellValue("123"+i);
row.createCell(1).setCellValue("123"+i);
row.createCell(2).setCellValue("123"+i);
row.createCell(3).setCellValue("123"+i);
row.createCell(4).setCellValue("123"+i);
row.createCell(5).setCellValue("123"+i);
row.createCell(6).setCellValue("123"+i);
row.createCell(7).setCellValue("123"+i);
}
// 生成Excel
FileOutputStream fos = new FileOutputStream(fileName);
workBook.write(fos);
fos.flush();
fos.close();
// 通知浏览器下载
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "utf-8")+".xlsx");
OutputStream outputStream = response.getOutputStream();
workBook.write(outputStream);
outputStream.flush();
outputStream.close();
respons.put("error", false);
respons.put("msg", "导出成功");
return JSON.toJSONString(respons, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero,
SerializerFeature.WriteNullBooleanAsFalse);
}
// 导出word
public String exportword(Map, ?> params, HttpServletResponse response) throws Exception {
Map respons = new HashMap();
XWPFDocument doc = new XWPFDocument();
XWPFParagraph p1 = doc.createParagraph();
p1.setAlignment(ParagraphAlignment.CENTER);
p1.setBorderBottom(Borders.DOUBLE);
p1.setBorderTop(Borders.DOUBLE);
p1.setBorderRight(Borders.DOUBLE);
p1.setBorderLeft(Borders.DOUBLE);
p1.setBorderBetween(Borders.SINGLE);
p1.setVerticalAlignment(TextAlignment.TOP);
XWPFRun r1 = p1.createRun();
r1.setBold(true);
r1.setText("The quick brown fox");
r1.setBold(true);
r1.setFontFamily("Courier");
r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH);
r1.setTextPosition(100);
XWPFParagraph p2 = doc.createParagraph();
p2.setAlignment(ParagraphAlignment.RIGHT);
//BORDERS
p2.setBorderBottom(Borders.DOUBLE);
p2.setBorderTop(Borders.DOUBLE);
p2.setBorderRight(Borders.DOUBLE);
p2.setBorderLeft(Borders.DOUBLE);
p2.setBorderBetween(Borders.SINGLE);
XWPFRun r2 = p2.createRun();
r2.setText("jumped over the lazy dog");
r2.setStrike(true);
r2.setFontSize(20);
XWPFRun r3 = p2.createRun();
r3.setText("and went away");
r3.setStrike(true);
r3.setFontSize(20);
r3.setSubscript(VerticalAlign.SUPERSCRIPT);
XWPFParagraph p3 = doc.createParagraph();
p3.setWordWrap(true);
p3.setPageBreak(true);
//p3.setAlignment(ParagraphAlignment.DISTRIBUTE);
p3.setAlignment(ParagraphAlignment.BOTH);
p3.setSpacingLineRule(LineSpacingRule.EXACT);
p3.setIndentationFirstLine(600);
XWPFRun r4 = p3.createRun();
r4.setTextPosition(20);
r4.setText("To be, or not to be: that is the question: "
+ "Whether 'tis nobler in the mind to suffer "
+ "The slings and arrows of outrageous fortune, "
+ "Or to take arms against a sea of troubles, "
+ "And by opposing end them? To die: to sleep; ");
r4.addBreak(BreakType.PAGE);
r4.setText("No more; and by a sleep to say we end "
+ "The heart-ache and the thousand natural shocks "
+ "That flesh is heir to, 'tis a consummation "
+ "Devoutly to be wish'd. To die, to sleep; "
+ "To sleep: perchance to dream: ay, there's the rub; "
+ ".......");
r4.setItalic(true);
//This would imply that this break shall be treated as a simple line break, and break the line after that word:
XWPFRun r5 = p3.createRun();
r5.setTextPosition(-10);
r5.setText("For in that sleep of death what dreams may come");
r5.addCarriageReturn();
r5.setText("When we have shuffled off this mortal coil,"
+ "Must give us pause: there's the respect"
+ "That makes calamity of so long life;");
r5.addBreak();
r5.setText("For who would bear the whips and scorns of time,"
+ "The oppressor's wrong, the proud man's contumely,");
r5.addBreak(BreakClear.ALL);
r5.setText("The pangs of despised love, the law's delay,"
+ "The insolence of office and the spurns" + ".......");
FileOutputStream out = new FileOutputStream("simple.docx");
doc.write(out);
out.close();
// 通知浏览器下载
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode("123", "utf-8")+".docx");
OutputStream outputStream = response.getOutputStream();
doc.write(outputStream);
outputStream.flush();
outputStream.close();
respons.put("error", false);
respons.put("msg", "导出成功");
return JSON.toJSONString(respons, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero,
SerializerFeature.WriteNullBooleanAsFalse);
}