注意:编码前先导入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. 22、JSON/jQuery上

      1)掌握JSON及其应用 2)了解jQuery的背景和特点 3)理解js对象和jQuery对象的区别 4)掌握jQuery九类选择器及应用(上)   声明:今天服务端我们使用Struts2技术 一 ...

  2. Python查看函数代码内容

    方法1:使用help(random) >>> import random >>> help(random) Help on module random: NAME ...

  3. python: 字符串按空格分成列表split与加密密码maketrans

    #字符串按空格分成列表split() print("fu li mei".split()) #split按空格分成列表 print("1+a+2+b".spli ...

  4. JSONArray传值的使用小结

    今天使用了SpringMVC+mybatis传值.从controller中传到service中.可是由于版本问题参数中不能有大写和下划线,在service中只能用String 来接受json字符串.接 ...

  5. windows tomcat配置大全

    Tomcat下JSP.Servlet和JavaBean环境的配置 第一步:下载j2sdk和tomcat:到sun官方站点()下载j2sdk,注意下载版本为Windows Offline Install ...

  6. poj3342 Party at Hali-Bula

    树形dp题,状态转移方程应该很好推,但一定要细心. http://poj.org/problem?id=3342 #include <cstdio> #include <cstrin ...

  7. Maximum Value(哈希)

    B. Maximum Value time limit per test 1 second memory limit per test 256 megabytes input standard inp ...

  8. Tautology 分类: POJ 2015-06-28 18:40 10人阅读 评论(0) 收藏

    Tautology Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 10428   Accepted: 3959 Descri ...

  9. 使用存储过程来动态调用数据(SELECT)

    USE [MyTestDb] GO /****** Object: StoredProcedure [dbo].[PROC_GetChannelList] Script Date: 04/09/201 ...

  10. 【20160924】GOCVHelper MFC增强算法(2)

    //创建或续写目录下的csv文件,填写“文件位置-分类”对     int writeCsv(const string& filename,const Vector<pair<st ...