java使用什么技术实现excel数据的批量导入导出
2017-01-06 · 百度知道合伙人官方认证企业
java使用第三方工具包POI技术实现excel数据的批量导入导出。
举例如下:
1、下载apache的相关jar包。poi-ooxml-3.6.jar xmlbeans-2.3.0.jar等,如图:
2、编写相关的读写类
/**
* 读取xls文件内容
*/
private
List<XlsDto> readXls() throws
IOException {
InputStream is = new
FileInputStream("test.xls");
HSSFWorkbook hssfWorkbook = new
HSSFWorkbook(is);
XlsDto xlsDto = null;
List<XlsDto> list = new
ArrayList<XlsDto>();
// 循环工作表Sheet
for
(int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
if
(hssfSheet == null) {
continue;
}
// 循环行Row
for
(int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
HSSFRow hssfRow = hssfSheet.getRow(rowNum);
if
(hssfRow == null) {
continue;
}
xlsDto = new
XlsDto();
// 循环列Cell
// 0学号 1姓名 2学院 3课程名 4 成绩
// for (int cellNum = 0; cellNum <=4; cellNum++) {
HSSFCell xh = hssfRow.getCell(0);
if
(xh == null) {
continue;
}
xlsDto.setXh(getValue(xh));
HSSFCell xm = hssfRow.getCell(1);
if
(xm == null) {
continue;
}
xlsDto.setXm(getValue(xm));
HSSFCell yxsmc = hssfRow.getCell(2);
if
(yxsmc == null) {
continue;
}
xlsDto.setYxsmc(getValue(yxsmc));
HSSFCell kcm = hssfRow.getCell(3);
if
(kcm == null) {
continue;
}
xlsDto.setKcm(getValue(kcm));
HSSFCell cj = hssfRow.getCell(4);
if
(cj == null) {
continue;
}
xlsDto.setCj(Float.parseFloat(getValue(cj)));
list.add(xlsDto);
}
}
return
list;
}
3、导出就是输入到一个新的excel文件里面
public void writeXls(List<Student> list, String path) throws Exception {
if (list == null) {原始数据为空,直接返回
return;
}
int countColumnNum = list.size();//设置列数
HSSFWorkbook book = new HSSFWorkbook(); //创建工作表对象
HSSFSheet sheet = book.createSheet("studentSheet");
// 创建第一行
HSSFRow firstRow = sheet.createRow(0);
HSSFCell[] firstCells = new HSSFCell[countColumnNum];
//创建表头
String[] options = { "no", "name", "age", "score" };
//循环数据域
for (int j = 0; j < options.length; j++) {
firstCells[j] = firstRow.createCell(j);
firstCells[j].setCellValue(new HSSFRichTextString(options[j]));
}
//处理每一个cell的值
for (int i = 0; i < countColumnNum; i++) {
HSSFRow row = sheet.createRow(i + 1);
Student student = list.get(i);
for (int column = 0; column < options.length; column++) {
HSSFCell no = row.createCell(0);
HSSFCell name = row.createCell(1);
HSSFCell age = row.createCell(2);
HSSFCell score = row.createCell(3);
no.setCellValue(student.getNo());
name.setCellValue(student.getName());
age.setCellValue(student.getAge());
score.setCellValue(student.getScore());
}
}
File file = new File(path);
OutputStream os = new FileOutputStream(file);
System.out.println(Common.WRITE_DATA + path);
book.write(os);
os.close();
}
广告 您可能关注的内容 |