注意:编码前先导入poi相关jar包
1 /**
* 读excel 到list
*
* @param file excel file
* @param fields 字段数组
* @return
* example OfficeHandle.readExcel("d:/test/test.xls",
* new String[]{"id","num","name"})
*/
public static JSONArray readExcel(String file,String[] fields){
if(null == file || null == fields)
return null; JSONArray jarr = new JSONArray();
FileInputStream fis = null;
int cols = 0;
try {
      /************************读取本地文件(如d:/test/test.xls)********************************************/
fis = new FileInputStream(new File(file));//读取本地文件(如d:/test/test.xls)
          HSSFWorkbook workbook = new HSSFWorkbook(fis);
      /**********************读取服务器文件(file="http://你的地址")******************************************/
URL url = new URL(file); //file="http://你的地址"
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
HSSFWorkbook workbook = new HSSFWorkbook(is);
      /**************************************************************************************************/
HSSFSheet sheet = workbook.getSheetAt(0);
if(sheet != null){
HSSFRow row = sheet.getRow(0);
if(row != null)
cols = row.getLastCellNum(); for(int i=1,len=sheet.getLastRowNum();i<=len;i++){
row = sheet.getRow(i);
if(row != null){
JSONObject jo = new JSONObject();
for(int j=0;j<cols;j++){
HSSFCell cell = row.getCell(j);
if(cell != null){
Object v=null;
HSSFCellStyle type = cell.getCellStyle();
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC:
v = cell.getNumericCellValue();
break;
case HSSFCell.CELL_TYPE_STRING:
v = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
v = cell.getBooleanCellValue();
break;
case HSSFCell.CELL_TYPE_FORMULA:
v = cell.getCellFormula();
break;
default:
System.out.println("unsuported sell type");
break;
}
jo.put(fields[j], v); }
}
jarr.add(jo);
}
}
}
} catch (FileNotFoundException e ) { }catch(IOException e){ }finally{
try {
fis.close();
} catch (IOException e) { }
}
return jarr;
} /**
* 从list生成excel
*
* @param lstData json array data
* @param fieldEn 字段英文名
* @param fieldZh 生成字段名
* @return
* example OfficeHandle.exportExcel(lstdata,
* new String[]{"schoolId","schoolno","schoolName","address","remarks","linkMobile","linkMan"},
* new String[]{"学校编号","","","","","",""},
* "d:/test/exel1.xls");
*/
public static String exportExcel(JSONArray lstData,String[] fieldEn,String[] fieldZh,String fname){
if(null == lstData || null == fieldEn)
return null; int fieldLen = fieldEn.length;
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
HSSFRow row = sheet.createRow(0);
for(int i=0;i<fieldLen;i++){
String fn = fieldEn[i];
if(null != fieldZh && !StringUtils.isEmpty(fieldZh[i])){
fn = fieldZh[i];
}
HSSFCell cell = row.createCell(i);
cell.setCellValue(fn);
}
for(int i=0,len=lstData.size();i<len;i++){
row = sheet.createRow(i+1);
for(int j=0;j<fieldLen;j++){
JSONObject jo = lstData.getJSONObject(i);
if(jo != null){
HSSFCell cell = row.createCell(j);
if(jo.containsKey(fieldEn[j])){
cell.setCellValue(jo.getString(fieldEn[j]));
}
}
}
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(fname);
workbook.write(fos); } catch (FileNotFoundException e) { e.printStackTrace();
}catch (IOException e) { }finally{
try {
fos.close();
} catch (IOException e) { }
}
return fname;
}

案例展示

 /**
* 导入excel数据
*/
public void importExcel(){
String x = null;
JSONArray jar = new JSONArray();
School sc = new School();
String[] fields = new String[]{"schoolId","schoolno","schoolName","address","remarks","linkMobile","linkMan"}; try{ jar = officHandle.readExcel(filePath, fields,true);
for(int i=0,len=jar.size();i<len;i++){
JSONObject ob = JSONObject.fromObject(jar.get(i));
String schoolno = ob.getString("schoolno");
if(!school.isExist(schoolno)){//根据学校编号判断,若不存在就添加否则更新
sc = (School)school.addRecord((School)JSONObject.toBean(ob,School.class));
}else{
School sch = (School)school.findByProperty("School", new String[]{"schoolno"}, new Object[]{schoolno}).get(0);//获取存在的记录id
ob.put("schoolId", sch.getSchoolId());
sc = (School)school.editRecord((School)JSONObject.toBean(ob,School.class));
}
}
x = sc.getSchoolId().toString();
}catch(Exception e){
x = errorHandle.handleErr(e);
}
servletHandle.writeToClient1(ServletActionContext.getResponse(), x);
}
 /**
* 导出数据到Excel
*/
public void exportData(){
String x = null;
String[] idArr = model.getIds().split(",");
List<School> schoolList = new ArrayList<School>();
JSONArray jar = new JSONArray();//数据list
String[] fieldEn = new String[]{"schoolno","schoolName","address","linkMobile","linkMan","remarks"};
String[] fieldCn = new String[]{"学校编号","学校名称","学校地址","联系电话","联系人","备注"};
try{
if(StringUtils.isEmpty(model.getIds())){//全部导出
x = school.findByProperty("School", "*",
"json", true,null, null, null, null, 0, 0);
schoolList = (List<School>) JSONObject.fromObject(x).get("rows");
if(schoolList.size() > 0){
for(int i=0,len=schoolList.size();i<len;i++){
jar.add(schoolList.get(i));
}
} }else{
for(int i=0,len=idArr.length;i<len;i++){//导出选择记录
schoolList = school.findByProperty("School", new String[]{"schoolId"}, new Object[]{Long.parseLong(idArr[i])});
if(schoolList.size() > 0)
jar.add(schoolList.get(0));
}
}
String basePath = ServletActionContext.getServletContext().getRealPath("/");//获取服务器文件存放地址
String path = "/assets/export/" + UUID.randomUUID().toString().replaceAll("-", "") + ".xls";//拼接随机生成文件名,用于写入excel数据流
String fn = basePath + path;
officHandle.exportExcel(jar, fieldEn, fieldCn, fn);//传入数据list,字段名及保存文件名
x = CommonConfig.domainName + CommonConfig.contextPath + path;//获取文件路径返回,location.href = x(浏览器自动下载文件)
}catch(Exception e){
x = errorHandle.handleErr(e);
}
servletHandle.writeToClient1(ServletActionContext.getResponse(), x);
}

java实现excel与mysql的导入导出的更多相关文章

  1. java中 Excel表实现数据导入导出

    需要引入依赖: <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency> < ...

  2. MySQL数据导入导出方法与工具mysqlimport

    MySQL数据导入导出方法与工具mysqlimport<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office ...

  3. MYSQL数据库导入导出(可以跨平台)

    MYSQL数据库导入导出.sql文件 转载地址:http://www.cnblogs.com/cnkenny/archive/2009/04/22/1441297.html 本人总结:直接复制数据库, ...

  4. mysql数据库导入导出 查询 修改表记录

    mysql数据导入导出: 导入: 把系统的文件的内容,保存到数据库的表里 导入数据的基本格式:mysql> load data infile "文件名" into table ...

  5. 学习 MySQL中导入 导出CSV

    学习 MySQL中导入 导出CSV http://blog.csdn.net/sara_yhl/article/details/6850107    速度是很快的 导出 select * from t ...

  6. MySql 利用mysql&mysqldum导入导出数据

    MySql 利用mysql&mysqldum导入导出数据 by:授客 QQ:1033553122   测试环境 Linux下测试,数据库MySql 工具 mysqldump,该命令位于mysq ...

  7. mysql执行导入导出数据源

    mysql执行导入导出数据源 一.导出数据表结构 导出数据库建表的结构,不带数据,windows环境下,在cmd下,执行: mysqldump –no-data –u username –p* dat ...

  8. MySQL数据导入导出(一)

    今天遇到一个需求,要用自动任务将一张表的数据导入另一张表.具体场景及限制:将数据库A中表A的数据导入到数据库B的表B中(增量数据或全量数据两种方式):体系1和体系2只能分别访问数据库A和数据库B.附图 ...

  9. Java实现Mysql数据导入导出

    package com.backup; import java.io.BufferedReader;import java.io.FileInputStream;import java.io.File ...

随机推荐

  1. PHP将多张小图拼接成一张大图

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> < ...

  2. HDU 1024:Max Sum Plus Plus(DP)

    http://acm.hdu.edu.cn/showproblem.php?pid=1024 Max Sum Plus Plus Problem Description Now I think you ...

  3. Effective STL

    第9条:慎重选择删除元素的方法 删除特定值元素,vector.string.deque用erase-remove:c.erase(remove(c.begin(),c.end(),1963),c.en ...

  4. css常用命名规则

    (一)常用的CSS命名规则 头:header 内容:content/container 尾:footer 导航:nav 侧栏:sidebar 栏目:column 页面外围控制整体布局宽度:wrappe ...

  5. [STL]set/multiset用法详解[自从VS2010开始,set的iterator类型自动就是const的引用类型]

    集合 使用set或multiset之前,必须加入头文件<set> Set.multiset都是集合类,差别在与set中不允许有重复元素,multiset中允许有重复元素. sets和mul ...

  6. ACM题目————Subsequence

    Description A sequence of N positive integers (10 < N < 100 000), each of them less than or eq ...

  7. 配置开发支持高并发TCP连接的Linux应用程序全攻略

    http://blog.chinaunix.net/uid-20733992-id-3447120.html http://blog.chinaunix.net/space.php?uid=16480 ...

  8. noi 7627 鸡蛋的硬度

    题目链接:http://noi.openjudge.cn/ch0206/7627/ 题目讲的二分其实是一个误导, d(i,j),表示当前最优策略时,最坏的情况下: 有 J 个鸡蛋,I 个可以怀疑的楼层 ...

  9. grails-shiro权限认证

    一.引用shiro插件 //在BuildConfig的plugins下面添加 compile ":shiro:1.2.1" 二.引用新插件后要进行编译 //grails命令 com ...

  10. 某代理网站免费IP地址抓取测试

    源代码在测试中... http://www.AAA.com/nn/|    122.6.107.107|    8888|    山东日照|    高匿|    HTTP|    |    |     ...