java poi 解析excel 输出json 并且拼接字符串显示到jsp

来源:互联网 发布:access vba编程入门 编辑:程序博客网 时间:2024/05/22 09:49

 

##js代码


$(function() {



            $("#file_form").submit(
                    function() {
                        //首先验证文件格式
                        var fileName = $('#file_input').val();
                        if (fileName === '') {
                            alert('select');
                            return false;
                        }
                        var fileType = (fileName.substring(fileName
                                .lastIndexOf(".") + 1, fileName.length))
                                .toLowerCase();
                        if (fileType !== 'xls' && fileType !== 'xlsx') {
                            alert('false,is not excel!');
                            return false;
                        }
                    $("#file_form").form("submit", {url:"demo/readExcel", onSubmit:function () {
                return $(this).form("validate");
                }, success:function (data) {
                console.log(data);
                var sql = $("#sql");
                sql.append(data);
                sql =data;
                if (data == "success") {
                alert("success");
                } else {
               
                }
               
                }});
                        
                        return false;
                    });


        });

    </script>

##jsp


<form id="file_form" action="uploadFile" enctype="multipart/form-data" method="post">
        <input type="file" name="file" id="file_input" value="file" /> 
        <input type="submit" value="upload" id='upFile-btn'>
        
    </form>




##java代码


package com.cn.controller;


import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


//import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


import com.jfinal.core.Controller;
import com.jfinal.upload.UploadFile;


public class readController extends Controller {


public void readExcel() {
UploadFile file = getFile("file");


file.getOriginalFileName();
File filepath = file.getFile();
String aa = "";


try {
aa =  Excel(filepath);
} catch (Exception e) {
// TODO: handle exception
}
renderText(aa);
}


/**
* 解析excel并且转换成字符串
*/
public static String Excel(File filepath) throws Exception {
// String fileType = filepath.substring(filepath.lastIndexOf(".") + 1,
// filepath.length());
// 流


InputStream is = new FileInputStream(filepath);
Workbook wb = null;
String sqlStr = "create table Tablist ( " + "\r\n";// 拼接的建表字符串
// try {
//// is = new FileInputStream(filepath);
//
// if (fileType.equals("xls")) {
// wb = new HSSFWorkbook(is);
// } else if (fileType.equals("xlsx")) {
wb = new XSSFWorkbook(is);


// } else {
// throw new Exception("该文件不是excel");
// }
int sheetSize = wb.getNumberOfSheets();

for (int i = 0;i < sheetSize;i++) {
Sheet sheet = wb.getSheetAt(i);
List<String> titles = new ArrayList<String>();// 放置所有的标题
int rowSize = sheet.getLastRowNum() + 1;
int j = 0;
while (j < rowSize) {
Row row = sheet.getRow(j);
while (row == null) {
continue;
}
;
int cellSize = row.getLastCellNum();// 行中有多少个单元格,也就是有多少列
if (j == 0) { // 第一行是标题行
int k = 0;
while (k < cellSize) {
Cell cell = row.getCell(k);
titles.add(cell.toString());
k++;
}


} else {
if (j != 1) {
sqlStr += "," + "\r\n";
}
int k = 0;
while (k < titles.size()) {
Cell cell = row.getCell(k);
// String key = titles.get(k);
int value = 0;
if (cell != null) {
if (k == 2) {
value = (int) Double.parseDouble(cell.toString());
sqlStr += "(" + value + ")";
} else if (k == 3) {
if ("否".equals(row.getCell(3).toString())) {
String con = "not null";
sqlStr += " " + con;
}


} else {
String str = cell.toString();
sqlStr += " " + str;
}


}


k++;
}
}


j++;
}

}


// } catch (Exception e) {
// throw e;
sqlStr += "\r\n" + ")";
System.out.println("sqlStr=+\r\n" + sqlStr);

return sqlStr;
}


}

这里主要讲java怎么实现读取excel       欢迎大家赏阅指正