1. 程式人生 > >apache poi處理excel表格

apache poi處理excel表格

匯入 apache poi jar包

excel檔案

jsp上傳excel檔案

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.8.3.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.ocupload-1.1.2.js"></script>
    <title>Title</title>

    <script type="text/javascript">
        $(function () {
            $("#button-import").upload({
                action: "${pageContext.request.contextPath}/regionAction_importExcel",
                name: "excelFile"
            })
        });
    </script>

</head>
<body>

<input type="button" id="uploadbtn" value="一鍵上傳">

</body>
</html>

讀取儲存資料庫

public class RegionAction extends BaseAction<Region> {

    @Autowired
    private RegionService regionService;

    private File excelFile;

    public RegionAction() throws IllegalAccessException, InstantiationException {
    }

    public void setExcelFile(File excelFile) {
        this.excelFile = excelFile;
    }

    public String importExcel() throws IOException {

        //System.out.println(excelFile.getAbsolutePath());

        HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(excelFile));

        HSSFSheet sheet = workbook.getSheetAt(0);
        List<Region> regions = new ArrayList<>();

        for (Row row : sheet) {

            String id = row.getCell(0).getStringCellValue();
            String province = row.getCell(1).getStringCellValue();
            String city = row.getCell(2).getStringCellValue();
            String district = row.getCell(3).getStringCellValue();
            String postcode = row.getCell(4).getStringCellValue();

            Region region = new Region(id, province, city, district, postcode);
            regions.add(region);
        }

        regions.remove(0);
        //儲存資料庫
        regionService.saveAll(regions);
        return SUCCESS;
    }
}