jxl读取excel实现导入excel写入数据库


@RequestMapping(params = "method=import", method = RequestMethod.POST) @ResponseBody public String importConfig(HttpServletRequest request, HttpServletResponse response) throws Exception{ response.setCharacterEncoding("GBK"); String result = new String();; try{ //获取请求中的文件 MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request; MultipartFile contentFile = multipartHttpServletRequest.getFile(IMPORT_FILE_NAME); //IMPORT_FILE_NAME为前端中input的name //读取请求中的excel Workbook workbook = Workbook.getWorkbook(contentFile.getInputStream()); Sheet sheet = workbook.getSheet(0); int rows=sheet.getRows(); int columns=sheet.getColumns(); //将excel中的内容读为ConfigInfo对象 List<ConfigInfo> listConfigInfo = new ArrayList<ConfigInfo>(); for(int i=1; i<rows; i++){ ConfigInfo configInfo = new ConfigInfo(); for(int j=0; j<columns; j++){ Cell cell = sheet.getCell(j, i); String cellContent = cell.getContents(); switch (j){ case 0 : configInfo.setDataId(cellContent); case 1 : configInfo.setGroup(cellContent); case 2 : configInfo.setContent(cellContent); } } listConfigInfo.add(configInfo); } //写入数据库 int importFailedNum = 0; for(ConfigInfo configInfo:listConfigInfo){ ConfigInfo configInfoExist = configService.findConfigInfo(configInfo.getDataId(), configInfo.getGroup()); //写入数据库之前判断是否存在该条配置,并记录 if (null != configInfoExist){ importFailedNum++;          }else{ try{ configService.addConfigInfo(configInfo.getDataId(), configInfo.getGroup(),configInfo.getContent()); }catch(Exception operationDatabaseException){ log.error("导入配置出错"+operationDatabaseException); return result; } } } result = String.valueOf(importFailedNum); return result; }catch(Exception exception){ log.error("导入配置出错"+exception); return result; } }

   

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html; charset=GBK" pageEncoding="GBK"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
<title>导入配置信息</title>
    <script src="../../../js/jquery.js" type="text/javascript"></script>
    <script src="../../../js/ajaxfileupload.js" type="text/javascript"></script>
    <style type="text/css">
        body td {
            color: #333;
            font-family: Arial, Helvetica, sans-serif;
            font-size: 10pt;
        }
    </style>
    <script type="text/javascript">
        $(function () {
            $(":button").click(function () {
                if ($("#contentFile").val().length > 0) {
                    ajaxFileUpload();
                }
                else {
                    alert("请选择文件");
                }
            })
        })
        function ajaxFileUpload() {
            $.ajaxFileUpload
            (
                {
                    url: '/diamond-server/admin.do?method=import', //用于文件上传的服务器端请求地址
                    secureuri: false, //一般设置为false
                    fileElementId: 'contentFile', //文件上传空间的id属性  <input type="file" id="file" name="file" />
                    dataType: 'JSON', //返回值类型 一般设置为json
                    type:'post',
                    success: function (data, status)  //服务器成功响应处理函数
                    {
                        //判断返回的值
                        if (data == 0)
                            alert("导入配置成功");
                        else
                            alert("错误!第"+data+"条配置导入失败,请仔细对比要导入的配置,不能与已存在的配置重复");
                        if (typeof (data.error) != 'undefined') {
                            if (data.error != '') {
                                alert(data.error);
                            } else {
                                alert(data.msg);
                            }
                        }
                        window.location.href = "list.jsp";
                    },
                    error: function (data, status, e)//服务器响应失败处理函数
                    {
                        alert(e);
                        window.location.href = "list.jsp";
                    }
                }
            )
            return false;
        }
    </script>
</head>
<body>
    <center><h1><strong>导入配置信息</strong></h1></center>
    <p align='center'>
        <input type="file" id="contentFile" name="contentFile" />
        <input type="button" value="上传" />
    </p>
</body>
</html>

     在MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;这句代码执行强转出错。发现我的配置文件里少了对multipart解析器的配置:

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <property name="maxUploadSize" value="104857600"/>  <!-- 文件最大的大小 -->
  <property name="maxInMemorySize" value="4096"/>
</bean>

同时需要依赖commons-fileupload-1.2.jar和commons-io-1.3.1。

 

转载于:https://www.cnblogs.com/pwenlee/p/4849519.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JXLJava Excel API的缩写,可以处理Excel文件的读取写入。以下是使用JXL进行Excel文件读取写入的示例代码: 1. 读取Excel文件: ```java import java.io.File; import java.util.ArrayList; import java.util.List; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; public class ExcelReader { public static void main(String[] args) { try { File file = new File("test.xls"); Workbook workbook = Workbook.getWorkbook(file); Sheet sheet = workbook.getSheet(0); int rowCount = sheet.getRows(); List<String[]> list = new ArrayList<String[]>(); for (int i = 0; i < rowCount; i++) { Cell[] cells = sheet.getRow(i); String[] row = new String[cells.length]; for (int j = 0; j < cells.length; j++) { row[j] = cells[j].getContents(); } list.add(row); } for (String[] row : list) { for (String cell : row) { System.out.print(cell + "\t"); } System.out.println(); } workbook.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 2. 写入Excel文件: ```java import java.io.File; import java.util.ArrayList; import java.util.List; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; public class ExcelWriter { public static void main(String[] args) { try { File file = new File("test.xls"); WritableWorkbook workbook = Workbook.createWorkbook(file); WritableSheet sheet = workbook.createSheet("Sheet1", 0); List<String[]> list = new ArrayList<String[]>(); list.add(new String[] {"Name", "Age", "Gender"}); list.add(new String[] {"Tom", "20", "Male"}); list.add(new String[] {"Lucy", "18", "Female"}); for (int i = 0; i < list.size(); i++) { String[] row = list.get(i); for (int j = 0; j < row.length; j++) { Label label = new Label(j, i, row[j]); sheet.addCell(label); } } workbook.write(); workbook.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 以上代码演示了如何使用JXL处理Excel文件的读取写入,通过这些示例代码,你可以根据自己的需要进行调整和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值