从 http://bus.aibang.com/cities-bus 中获取城市列表和对应的链接存储到excel文件中。
下载jsoup jar包和poi jar包
City.java
package dataToExcel;
public class City {
private String name;
private String url;
public City(String name, String url) {
super();
this.name = name;
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
- CitiesToExcel.java
package dataToExcel;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class CitiesToExcel {
/**
* @Method Description 获得一个List对象,其中的数据使用网络爬虫从网站上爬取
*
* */
public static List<City> getCityList() throws IOException{
List<City> cityList = new ArrayList<City>();
Document doc = Jsoup.connect("http://bus.aibang.com/cities-bus").get();
Elements uls = doc.getElementsByTag("ul");
Element ul = uls.get(1);
Elements lis = ul.getElementsByTag("li");
for(int i = 0;i<lis.size();i++){
Element li = lis.get(i);
Elements as = li.getElementsByTag("a");
for(int j = 0;j<as.size();j++){
Element a = as.get(j);
String cityname = a.text();
String cityurl = a.attr("href");
cityList.add(new City(cityname,cityurl));
}
}
return cityList;
}
/**
* @Method Description 将数据写入一个excel表格
* */
public static void main(String[] args) throws IOException {
//第一步 创建一个webbook 对应一个excel文件
HSSFWorkbook wb = new HSSFWorkbook();
//第二步 在webbook中添加一个sheet,对应excel中的sheet
HSSFSheet sheet = wb.createSheet("表一");
//第三步 在sheet中添加表头第0行 注意老版本poi对Excel的行数列数有限制short
HSSFRow row = sheet.createRow(0);
// 第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style =wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //创建一个居中格式
HSSFCell cell1 = row.createCell(0);
cell1.setCellValue("城市名");
cell1.setCellStyle(style);
HSSFCell cell2 = row.createCell(1);
cell2.setCellValue("URL");
cell2.setCellStyle(style);
//第五步 写入数据 从网络中爬取下来
List<City> list = getCityList();
for(int i = 0;i<list.size();i++){
row = sheet.createRow(i+1);
//第四步 创建单元格 并设置值
row.createCell(0).setCellValue(list.get(i).getName());
row.createCell(1).setCellValue(list.get(i).getUrl());
}
//第六步 将文件存储到指定位置
try{
FileOutputStream fos = new FileOutputStream("city_url.xls");
wb.write(fos);
fos.flush();
fos.close();
}catch(Exception e){
e.printStackTrace();
}
}
}