第一个是高德地图接口返回的数据对象的domain类
@Getter @Setter
public class DataClass {
private String name; //名称
private String pname;//poi所在省份名称 若是直辖市的时候,此处直接显示市名,例如北京市
private String cityname;//城市名 若是直辖市的时候,此处直接显示市名,例如北京市
private String adname;//区域名称 区县级别的返回,例如朝阳区
private String address; // 地址 东四环中路189号百盛北门
private String location; //经纬度 格式:X,Y
private String tel; //该POI的电话
private String distance; //离中心点距离 单位:米 必须说明, 此结果仅在周边搜索的时候有值
private String LON;//经
private String LAT;//纬
private String photos;//照片集
private String picOss;//照片上传到服务器之后返回的url
}
第二个类是Controller类 用户访问的接口
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/demo")
public class DownLoadExcelForXXXYEWUController {
@Resource
private XXXXMapper xxxxmapper;
@RequestMapping(value = "demoInfo", method = RequestMethod.GET)
@ResponseBody
public String ExportDataByExcel(String code, String page, HttpServletRequest req, HttpServletResponse resp) {
if (StringUtils.isEmpty(code) || StringUtils.isEmpty(page)) {
return "输入的参数有误!";
}
// Excel标题
String title = "导出excel表格";
// 列名
String[] rowsName = new String[] { "序号", "XX名称", "XX类型", "XX头像", "XX联系电话(固话)", "XX经度", "XX纬度", "省份", "城市", "区",
"街道", "具体地址", "XX星级" };
// 新建数据集合
List dataList = new ArrayList();
Object[] objs = null;
GetDataFromGaoDe t = new GetDataFromGaoDe();
//拿到高德接口返回的数据
List resultData = t.getDate(code, page);
if (null != resultData && !resultData.isEmpty()) {
for (int i = 0; i < resultData.size(); i++) {
//拿到每一个DataClass数据对象
DataClass data = resultData.get(i);
objs = new Object[rowsName.length];
objs[0] = i;//序号
objs[1] = StringUtils.isEmpty(data.getName()) ? " " : data.getName();//XXX名称
objs[2] = "XXXX";//XXX类型
objs[3] = " ";//XXX图片
objs[4] = StringUtils.isEmpty(data.getTel()) ? " " : data.getTel();//联系方式
objs[5] = StringUtils.isEmpty(data.getLON()) ? " " : data.getLON();//经度
objs[6] = StringUtils.isEmpty(data.getLAT()) ? " " : data.getLAT();//纬度
objs[7] = StringUtils.isEmpty(data.getPname()) ? " " : data.getPname();//省份
objs[8] = StringUtils.isEmpty(data.getCityname()) ? " " : data.getCityname();//城市
objs[9] = StringUtils.isEmpty(data.getAdname()) ? " " : data.getAdname();//区
objs[10] = " ";//街道
objs[11] = StringUtils.isEmpty(data.getAddress()) ? " " : data.getAddress();//具体地址
objs[12] = "可以继续自定义";//自定义
dataList.add(objs);
}
}
ExcelUtil ex = new ExcelUtil(title, rowsName, dataList);
try {
ex.export(req, resp);
} catch (Exception e) {
e.printStackTrace();
}
if (null != resultData && !resultData.isEmpty()) {
for (DataClass data : resultData) {
XxxRegistrationVO insertParam = new XxxRegistrationVO();
if (StringUtils.isNotEmpty(data.getLAT()) && StringUtils.isNotEmpty(data.getLON())) {
insertParam.setLat(Double.valueOf(data.getLAT()));
insertParam.setLon(Double.valueOf(data.getLON()));
}
insertParam.setCheckPerson((long) 100);
// 发现联系电话有问题,截取一下
if (StringUtils.isNotEmpty(data.getTel()) && data.getTel().length() >= 7) {
if (!"[]".equals(data.getTel())) {
String[] phones = data.getTel().split(";");
// String phone = data.getTel().substring(0, 11);
insertParam.setEdtPhone(phones[0]);
}
}
insertParam.setHeadUrl(data.getPicOss());
insertParam.setProvice(data.getPname());// 省
insertParam.setCity(data.getCityname());// 市
insertParam.setArea(data.getAdname());// 区
// insertParam.setStreet(data.getAdname());//街道
insertParam.setAddress(data.getAddress());// 具体地址
insertParam.setClassify("1");
insertParam.setXxxType("1");
insertParam.setXxxName(data.getName());
insertParam.setXxxRegistInfo("运营活动上线XXX");
//插入数据库
//xxxxmapper.add(insertParam);
}
}
return "已经完成下载!";
}
}
这是Excel导出的工具类
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.HSSFRichTextString;
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.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;
/**
* 导出Excel公共方法
* @version 1.0
*
* @author wangcp
*
*/
@SuppressWarnings("deprecation")
public class ExcelUtil {
private String title;//显示的导出表的标题
private String[] rowName; //导出表的列名
private List dataList = new ArrayList();//数据集合
HttpServletResponse response;
//构造方法,传入要导出的数据
public ExcelUtil(String title,String[] rowName,List dataList){
this.dataList = dataList;
this.rowName = rowName;
this.title = title;
}
/*
* 导出数据
* */
public void export(HttpServletRequest req, HttpServletResponse resp) throws Exception{
try{
HSSFWorkbook workbook = new HSSFWorkbook();// 创建工作簿对象
HSSFSheet sheet = workbook.createSheet(title);// 创建工作表
// 产生表格标题行
HSSFRow rowm = sheet.createRow(0);
HSSFCell cellTiltle = rowm.createCell(0);
//sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面 - 可扩展】
HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);//获取列头样式对象
HSSFCellStyle style = this.getStyle(workbook); //单元格样式对象
//合并地区 : 0行 0列 ---1行 列的长度
sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length-1)));
//设置第一行的表格标题类型
cellTiltle.setCellStyle(columnTopStyle);
//设置第一行的表格标题内容
cellTiltle.setCellValue(title);
// 定义所需列数
int columnNum = rowName.length;
HSSFRow rowRowName = sheet.createRow(2);//在索引2的位置创建行(最顶端的行开始的第二行,此时第一行是标题)
// 将列头设置到sheet的单元格中
for(int n=0;n //创建列头对应个数的单元格
HSSFCell cellRowName = rowRowName.createCell(n);
//设置列头单元格的数据类型
cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING);
//拿到各个列头名
HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
//设置列头单元格的值、设置列头单元格样式
cellRowName.setCellValue(text);
cellRowName.setCellStyle(columnTopStyle);
}
//将查询出的数据设置到sheet对应的单元格中
//循环数据对象个数
for(int i=0;i //遍历每个对象
Object[] obj = dataList.get(i);
//创建所需的行数(加上标题的最开始的两行,所以索引+3)
HSSFRow row = sheet.createRow(i+3);
for(int j=0; j //在row行里
if(j == 0){
cell = row.createCell(j,HSSFCell.CELL_TYPE_NUMERIC);
cell.setCellValue(i+1);
}else{
cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING);
if(!"".equals(obj[j]) && obj[j] != null){
cell.setCellValue(obj[j].toString());//设置单元格的值
}
}
cell.setCellStyle(style);//设置单元格样式
}
}
//让列宽随着导出的列长自动适应
for (int colNum = 0; colNum < columnNum; colNum++) {
int columnWidth = sheet.getColumnWidth(colNum) / 256;
for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
HSSFRow currentRow;
//当前行未被使用过
if (sheet.getRow(rowNum) == null) {
currentRow = sheet.createRow(rowNum);
} else {
currentRow = sheet.getRow(rowNum);
}
if (currentRow.getCell(colNum) != null) {
HSSFCell currentCell = currentRow.getCell(colNum);
if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
int length = currentCell.getStringCellValue().getBytes().length;
if (columnWidth < length) {
columnWidth = length;
}
}
}
}
if(colNum == 0){
sheet.setColumnWidth(colNum, (columnWidth-2) * 256);
}else{
sheet.setColumnWidth(colNum, (columnWidth+4) * 256);
}
}
if(workbook !=null){
try
{
String fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls";
String headStr = "attachment; filename=\"" + fileName + "\"";
//response = ((ServletWebRequest) RequestContextHolder.getRequestAttributes())).getResponse();
response = resp;
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", headStr);
OutputStream out = response.getOutputStream();
workbook.write(out);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}catch(Exception e){
e.printStackTrace();
}
}
/*
* 列头单元格样式
*/
public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {
// 设置字体
HSSFFont font = workbook.createFont();
//设置字体大小
font.setFontHeightInPoints((short)11);
//字体加粗
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//设置字体名字
font.setFontName("Courier New");
//设置样式;
HSSFCellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//设置左边框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//设置右边框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//设置顶边框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
return style;
}
/*
* 列数据信息单元格样式
*/
public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
// 设置字体
HSSFFont font = workbook.createFont();
//设置字体大小
//font.setFontHeightInPoints((short)10);
//字体加粗
//font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//设置字体名字
font.setFontName("Courier New");
//设置样式;
HSSFCellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//设置左边框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//设置右边框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//设置顶边框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
return style;
}
}
getData()方法:
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class GetDataFromGaoDe {
public List getDate(String code, String page) {
List result = new ArrayList();
try {
StringBuffer send = new StringBuffer();
send.append("&key=").append("8325164e247e15eea68b59e89200988b");
// send.append("&page=").append("1");
send.append("&page=").append(page);
send.append("&city=").append(code);
send.append("&offset=").append("20");
send.append("&keywords=").append(URLEncoder.encode("在高德地图搜索的关键字", "UTF-8"));// 中文编码
// city编码查询网址(http://lbs.amap.com/api/javascript-api/reference-amap-ui/geo/district-explorer)
// send.append("&city=").append("440403");
send.append("&citylimit=").append("true");
send.append("&language=").append("zh_cn");
send.append("&extensions=").append("all");
String data = SmsClientAccessTool.getInstance().doAccessHTTPPost("http://restapi.amap.com/v3/place/text",
send.toString(), "UTF-8");
if (data != null) {// 循环读取数据
/*
* System.out.println(data); String dateSub = data.substring(14, data.length());
* JSONObject obj = JSONObject.parseObject(dateSub.substring(0, dateSub.length()
* - 1));
*/
// 把data转换成json类型对象
JSONObject obj = JSONObject.parseObject(data);
// 拿到pois数组,并把数组转换成json类型数组
JSONArray arraylist = JSONArray.parseArray(obj.getString("pois"));
// 迭代pois
if (arraylist != null && !arraylist.isEmpty()) {
for (int i = 0; i < arraylist.size(); i++) {
// 每一个pois的对象都是一个结果
DataClass date = JSON.parseObject(arraylist.getJSONObject(i).toJSONString(), DataClass.class);
if (date != null && StringUtils.isNotEmpty(date.getLocation())) {
String[] longitudeAndLatitude = date.getLocation().split(",");
// 获得经纬度
if (null != longitudeAndLatitude && 2 == longitudeAndLatitude.length) {
date.setLAT(longitudeAndLatitude[1]);
date.setLON(longitudeAndLatitude[0]);
}
// 处理图片信息
if (StringUtils.isNotEmpty(date.getPhotos())) {
//如果照片相关信息不为空
JSONArray photoList = JSONArray.parseArray(date.getPhotos());
if (null != photoList && !photoList.isEmpty()) {
//取第一张图片
JSONObject gaodePic = JSONObject.parseObject(photoList.getString(0));
//拿到照片的url
String pic = gaodePic.getString("url");
if (StringUtils.isNotEmpty(pic)) {
String path = "H:/pic/" + UUID.randomUUID() + ".jpg";
downloadPicture(pic, path);
String resultUrl = OSSUploadUtil.uploadFile(new File(path), "jpg",
"institution/");
date.setPicOss(resultUrl);
}
}
}
}
result.add(date);
}
}
/*
* System.out.println(JSONObject.toJSONString(result)); data = br.readLine();
*/
}
} catch (
Exception e) {
e.printStackTrace();
}
return result;
}
// 链接url下载图片
/**
*
* @param urlList 照片url
* @param path 下载目的路径
*/
private static void downloadPicture(String urlList, String path) {
URL url = null;
try {
//新建图片url
url = new URL(urlList);
//新建数据输入流
DataInputStream dataInputStream = new DataInputStream(url.openStream());
//新建文件输出流
FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
//数组输出流
ByteArrayOutputStream output = new ByteArrayOutputStream();
//btye类型数组
byte[] buffer = new byte[1024];
//长度
int length;
//当输入流能读到长度
while ((length = dataInputStream.read(buffer)) > 0) {
//输出流写长度
output.write(buffer, 0, length);
}
//文件类型的输出流写二进制文件
fileOutputStream.write(output.toByteArray());
dataInputStream.close();
fileOutputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}