助于apathe的poi.jar,由于不支持上传文件,所以请自行百度下载poi.jar,在应用程序中添加poi.jar包,并将需要读取的excel文件放入根目录即可。
本例使用java来读写excel的内容,代码如下:
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
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.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
public class PoiExpExcel {
private static final File file = new File("poi_test.xls");
/**
* 导出Excel
*/
private static void exportExcel() {
String[] title = {"id","name","sex"};
//创建Excel工作簿
HSSFWorkbook workbook = new HSSFWorkbook();
//创建一个工作表sheet
Sheet sheet = workbook.createSheet("信息表");
//创建第一行
Row row = sheet.createRow(0);
Cell cell = null;
//插入第一行数据 id,name,sex
for(int i = 0; i < title.length; i++) {
cell = row.createCell(i);
cell.setCellValue(title[i]);
}
//追加数据
//行从0开始,去除第一行标题,这里从第2行开始追加
for(int i = 1; i < 10; i++) {
Row nextrow = sheet.createRow(i);
//列从0开始
//第1列
cell = nextrow.createCell(0);
cell.setCellValue("a" + i);
//第2列
cell = nextrow.createCell(1);
cell.setCellValue("user" + i);
//第3列
cell = nextrow.createCell(2);
cell.setCellValue("男");
}
try {
if(!file.exists())
file.createNewFile();
//将Excel内容存储
FileOutputStream stream = new FileOutputStream(file);
workbook.write(stream);
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 导入Excel
*/
public static void importExcel() {
POIFSFileSystem fs;
try {
fs = new POIFSFileSystem(new BufferedInputStream(new FileInputStream(file)));
HSSFWorkbook workbook = new HSSFWorkbook(fs);
for(int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); ++sheetIndex) {
HSSFSheet sheet = workbook.getSheetAt(sheetIndex); //形同workbook.getSheet("信息表");
//第一行为标题,不取,故从1开始
for(int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); ++rowIndex) {
//第一列开始去,从0开始
int columnIndex = 0;
HSSFRow row = sheet.getRow(rowIndex);
HSSFCell cell = row.getCell(columnIndex++);
String id = cell.getStringCellValue();
cell = row.getCell(columnIndex++);
String name = cell.getStringCellValue();
cell = row.getCell(columnIndex++);
String sex = cell.getStringCellValue();
System.out.println("id:" + id + " name:" + name + " sex:" + sex);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//导出Excel
exportExcel();
//导入Excel
importExcel();
}
}
展示打印结果:
id:a1 name:user1 sex:男
id:a2 name:user2 sex:男
id:a3 name:user3 sex:男
id:a4 name:user4 sex:男
id:a5 name:user5 sex:男
id:a6 name:user6 sex:男
id:a7 name:user7 sex:男
id:a8 name:user8 sex:男
id:a9 name:user9 sex:男