Apache POI 下載下傳 - 建立Excel表
public class Test {
/** 存儲路徑 */
private static String path = "E:/Student.xls";
/** 清單資訊 */
private static List<Student> mList;
/** 工作簿 */
private static HSSFWorkbook workbook;
/** 格式化時間 */
static SimpleDateFormat dateFormat;
static {
mList = new ArrayList<Student>();
dateFormat = new SimpleDateFormat("yyyy-mm-dd");
try {
Student user1 = new Student(1, "張三", 16, dateFormat.parse("1997-03-12"));
Student user2 = new Student(2, "李四", 17, dateFormat.parse("1996-08-12"));
Student user3 = new Student(3, "王五", 26, dateFormat.parse("1985-11-12"));
mList.add(user1);
mList.add(user2);
mList.add(user3);
} catch (ParseException e) {
e.printStackTrace();
}
}
/**
* 主函數
*/
public static void main(String[] args) {
// 建立一個工作簿
workbook = new HSSFWorkbook();
// 第二步, 在WebBook中添加一個sheet,對應Excel中的sheet
HSSFSheet sheet = workbook.createSheet("學生表一");
// 第三步, 在sheet中添加表頭第0行
HSSFRow row = sheet.createRow(0);
// 第四步, 建立單元格, 并設定值表頭, 設定表頭居中
HSSFCellStyle style = workbook.createCellStyle();
// 建立一個居中顯示的頭
style.setAlignment(HorizontalAlignment.CENTER);
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// 建立第一行
HSSFCell cell = row.createCell(0);
cell.setCellValue("學号");
cell.setCellStyle(style);
cell = row.createCell(1);
cell.setCellValue("姓名");
cell.setCellStyle(style);
cell = row.createCell(2);
cell.setCellValue("年齡");
cell.setCellStyle(style);
cell = row.createCell(3);
cell.setCellValue("生日");
cell.setCellStyle(style);
String[] textlist = { "16", "17", "26", "20", "23" };
// 建立下拉清單
sheet = setHSSFValidation(sheet, textlist, 0, 500, 2, 2);
// 寫入實體資料
for (int i = 0; i < mList.size(); i++) {
row = sheet.createRow(i + 1);
Student student = mList.get(i);
// 第四步,建立單元格并設定值
row.createCell(0).setCellValue(student.getId());
row.createCell(1).setCellValue(student.getName());
row.createCell(2).setCellValue(student.getAge());
row.createCell(3).setCellValue(dateFormat.format(student.getBirth()));
}
try {
FileOutputStream fos = new FileOutputStream(path);
workbook.write(fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 設定某些列的值隻能輸入預制的資料,顯示下拉框.
* @param sheet 要設定的sheet.
* @param textlist 下拉框顯示的内容
* @param firstRow 開始行
* @param endRow 結束行
* @param firstCol 開始列
* @param endCol 結束列
* @return 設定好的sheet.
*/
private static HSSFSheet setHSSFValidation(HSSFSheet sheet, String[] textlist, int firstRow, int lastRow,
int firstCol, int lastCol) {
// 加載下拉清單内容
DVConstraint constraint = DVConstraint.createExplicitListConstraint(textlist);
// 設定資料有效性加載在哪個單元格上,四個參數分别是:起始行、終止行、起始列、終止列
CellRangeAddressList regions = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);
// 資料有效性對象
HSSFDataValidation dataValidation = new HSSFDataValidation(regions, constraint);
sheet.addValidationData(dataValidation);
return sheet;
}
/**
* 設定單元格上提示
* @param sheet 要設定的sheet.
* @param promptTitle 标題
* @param promptContent 内容
* @param firstRow 開始行
* @param endRow 結束行
* @param firstCol 開始列
* @param endCol 結束列
* @return 設定好的sheet.
*/
public static HSSFSheet setHSSFPrompt(HSSFSheet sheet, String promptTitle,
String promptContent, int firstRow, int endRow ,int firstCol,int endCol) {
// 構造constraint對象
DVConstraint constraint = DVConstraint.createCustomFormulaConstraint("BB1");
// 四個參數分别是:起始行、終止行、起始列、終止列
CellRangeAddressList regions = new CellRangeAddressList(firstRow,endRow,firstCol, endCol);
// 資料有效性對象
HSSFDataValidation data_validation_view = new HSSFDataValidation(regions,constraint);
data_validation_view.createPromptBox(promptTitle, promptContent);
sheet.addValidationData(data_validation_view);
return sheet;
}
}
- 讀取Excel表
/**
* 讀取Excel表格的功能類
*/
public class ExcelReader {
private POIFSFileSystem fs;
private HSSFWorkbook wb;
private HSSFSheet sheet;
private HSSFRow row;
/**
* 讀取Excel表格表頭的内容
* @param InputStream
* @return String 表頭内容的數組
*/
public String[] readExcelTitle(InputStream is) {
try {
fs = new POIFSFileSystem(is);
wb = new HSSFWorkbook(fs);
} catch (IOException e) {
e.printStackTrace();
}
sheet = wb.getSheetAt(0);
row = sheet.getRow(0);
// 标題總列數
int colNum = row.getPhysicalNumberOfCells();
System.out.println("colNum:" + colNum);
String[] title = new String[colNum];
for (int i = 0; i < colNum; i++) {
//title[i] = getStringCellValue(row.getCell((short) i));
title[i] = getCellFormatValue(row.getCell((short) i));
}
return title;
}
/**
* 讀取Excel資料内容
* @param InputStream
* @return Map 包含單元格資料内容的Map對象
*/
public Map<Integer, String> readExcelContent(InputStream is) {
Map<Integer, String> content = new HashMap<Integer, String>();
String str = "";
try {
fs = new POIFSFileSystem(is);
wb = new HSSFWorkbook(fs);
} catch (IOException e) {
e.printStackTrace();
}
sheet = wb.getSheetAt(0);
// 得到總行數
int rowNum = sheet.getLastRowNum();
row = sheet.getRow(0);
int colNum = row.getPhysicalNumberOfCells();
// 正文内容應該從第二行開始,第一行為表頭的标題
for (int i = 1; i <= rowNum; i++) {
row = sheet.getRow(i);
int j = 0;
while (j < colNum) {
// 每個單元格的資料内容用"-"分割開,以後需要時用String類的replace()方法還原資料
// 也可以将每個單元格的資料設定到一個javabean的屬性中,此時需要建立一個javabean
// str += getStringCellValue(row.getCell((short) j)).trim() +
// "-";
str += getCellFormatValue(row.getCell((short) j)).trim() + " ";
j++;
}
content.put(i, str);
str = "";
}
return content;
}
/**
* 擷取單元格資料内容為字元串類型的資料
*
* @param cell Excel單元格
* @return String 單元格資料内容
*/
private String getStringCellValue(HSSFCell cell) {
if (null == cell) {
return "";
}
String strCell = "";
switch (cell.getCellTypeEnum()) {
case STRING:
strCell = cell.getStringCellValue();
break;
case NUMERIC:
strCell = String.valueOf(cell.getNumericCellValue());
break;
case BOOLEAN:
strCell = String.valueOf(cell.getBooleanCellValue());
break;
case BLANK:
strCell = "";
break;
default:
strCell = "";
break;
}
if (strCell.equals("") || strCell == null) {
return "";
}
return strCell;
}
/**
* 擷取單元格資料内容為日期類型的資料
*
* @param cell
* Excel單元格
* @return String 單元格資料内容
*/
private String getDateCellValue(HSSFCell cell) {
String result = "";
try {
CellType cellType = cell.getCellTypeEnum();
if (cellType == CellType.NUMERIC) {
Date date = cell.getDateCellValue();
result = (date.getYear() + 1900) + "-" + (date.getMonth() + 1)
+ "-" + date.getDate();
} else if (cellType == CellType.STRING) {
String date = getStringCellValue(cell);
result = date.replaceAll("[年月]", "-").replace("日", "").trim();
} else if (cellType == CellType.BLANK) {
result = "";
}
} catch (Exception e) {
System.out.println("日期格式不正确!");
e.printStackTrace();
}
return result;
}
/**
* 根據HSSFCell類型設定資料
* @param cell
* @return
*/
private String getCellFormatValue(HSSFCell cell) {
String cellvalue = "";
if (cell != null) {
// 判斷目前Cell的Type
switch (cell.getCellTypeEnum()) {
// 如果目前Cell的Type為NUMERIC
case NUMERIC:
case FORMULA: {
// 判斷目前的cell是否為Date
if (HSSFDateUtil.isCellDateFormatted(cell)) {
// 如果是Date類型則,轉化為Data格式
//方法1:這樣子的data格式是帶時分秒的:2011-10-12 0:00:00
//cellvalue = cell.getDateCellValue().toLocaleString();
//方法2:這樣子的data格式是不帶帶時分秒的:2011-10-12
Date date = cell.getDateCellValue();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
cellvalue = sdf.format(date);
}
// 如果是純數字
else {
// 取得目前Cell的數值
cellvalue = String.valueOf(cell.getNumericCellValue());
}
break;
}
// 如果目前Cell的Type為STRIN
case STRING:
// 取得目前的Cell字元串
cellvalue = cell.getRichStringCellValue().getString();
break;
// 預設的Cell值
default:
cellvalue = " ";
}
} else {
cellvalue = "";
}
return cellvalue;
}
/** 存儲路徑 */
private static String path = "E:/Student.xls";
public static void main(String[] args) {
try {
// 對讀取Excel表格标題測試
InputStream is = new FileInputStream(path);
ExcelReader excelReader = new ExcelReader();
String[] title = excelReader.readExcelTitle(is);
System.out.println("獲得Excel表格的标題:");
for (String s : title) {
System.out.print(s + " ");
}
System.out.println("");
// 對讀取Excel表格内容測試
InputStream is2 = new FileInputStream(path);
Map<Integer, String> map = excelReader.readExcelContent(is2);
System.out.println("獲得Excel表格的内容:");
for (int i = 1; i <= map.size(); i++) {
System.out.println(map.get(i));
}
} catch (FileNotFoundException e) {
System.out.println("未找到指定路徑的檔案!");
e.printStackTrace();
}
}
}