利用idea创建java web的maven项目,在pom中添加对poi的jar的依赖。
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 3 <modelVersion>4.0.0modelVersion> 4 <groupId>com.handgroupId> 5 <artifactId>excel-dataartifactId> 6 <packaging>warpackaging> 7 <version>1.0-SNAPSHOTversion> 8 <name>excel-data Maven Webappname> 9 <url>http://maven.apache.orgurl> 10 <dependencies> 11 <dependency> 12 <groupId>junitgroupId> 13 <artifactId>junitartifactId> 14 <version>3.8.1version> 15 <scope>testscope> 16 dependency> 17 <dependency> 18 <groupId>org.apache.poigroupId> 19 <artifactId>poiartifactId> 20 <version>3.14version> 21 dependency> 22 dependencies> 23 <build> 24 <finalName>excel-datafinalName> 25 build> 26 project>
web.xml中配置下后续导出时,所需要的servlet映射信息:
1 DOCTYPE web-app PUBLIC 2 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 3 "http://java.sun.com/dtd/web-app_2_3.dtd" > 4 5 <web-app> 6 <display-name>Archetype Created Web Applicationdisplay-name> 7 <servlet> 8 <servlet-name>TestServletservlet-name> 9 <servlet-class>TestServletservlet-class> 10 servlet> 11 12 <servlet-mapping> 13 <servlet-name>TestServletservlet-name> 14 <url-pattern>/TestServleturl-pattern> 15 servlet-mapping> 16 web-app>
Excel导入工具类实现:
1 import org.apache.poi.hssf.usermodel.*; 2 import org.apache.poi.poifs.filesystem.POIFSFileSystem; 3 import java.io.FileInputStream; 4 import java.io.FileNotFoundException; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.text.SimpleDateFormat; 8 import java.util.Date; 9 import java.util.HashMap; 10 import java.util.Map; 11 12 /** 13 * @author [email protected] 14 * @version 1.0 15 * @name 16 * @description 读取并解析excel 17 * @date 2017/10/19 18 */ 19 public class ImportExcel { 20 21 private POIFSFileSystem fs; 22 private HSSFWorkbook wb; 23 private HSSFSheet sheet; 24 private HSSFRow row; 25 26 /** 27 * 读取Excel表格表头的内容 28 * @param is 29 * @return String 表头内容的数组 30 */ 31 public String[] readExcelTitle(InputStream is) { 32 try { 33 fs = new POIFSFileSystem(is); 34 wb = new HSSFWorkbook(fs); 35 } catch (IOException e) { 36 e.printStackTrace(); 37 } 38 sheet = wb.getSheetAt(0); 39 //得到首行的row 40 row = sheet.getRow(0); 41 // 标题总列数 42 int colNum = row.getPhysicalNumberOfCells(); 43 String[] title = new String[colNum]; 44 for (int i = 0; i < colNum; i++) { 45 title[i] = getCellFormatValue(row.getCell((short) i)); 46 } 47 return title; 48 } 49 50 /** 51 * 读取Excel数据内容 52 * @param is 53 * @return Map 包含单元格数据内容的Map对象 54 */ 55 public MapreadExcelContent(InputStream is) { 56 Map content = new HashMap (); 57 String str = ""; 58 try { 59 fs = new POIFSFileSystem(is); 60 wb = new HSSFWorkbook(fs); 61 } catch (IOException e) { 62 e.printStackTrace(); 63 } 64 sheet = wb.getSheetAt(0); 65 // 得到总行数 66 int rowNum = sheet.getLastRowNum(); 67 //由于第0行和第一行已经合并了 在这里索引从2开始 68 row = sheet.getRow(2); 69 int colNum = row.getPhysicalNumberOfCells(); 70 // 正文内容应该从第二行开始,第一行为表头的标题 71 for (int i = 2; i <= rowNum; i++) { 72 row = sheet.getRow(i); 73 int j = 0; 74 while (j < colNum) { 75 str += getCellFormatValue(row.getCell((short) j)).trim() + "-"; 76 j++; 77 } 78 content.put(i, str); 79 str = ""; 80 } 81 return content; 82 } 83 84 /** 85 * 获取单元格数据内容为字符串类型的数据 86 * 87 * @param cell Excel单元格 88 * @return String 单元格数据内容 89 */ 90 private String getStringCellValue(HSSFCell cell) { 91 String strCell = ""; 92 switch (cell.getCellType()) { 93 case HSSFCell.CELL_TYPE_STRING: 94 strCell = cell.getStringCellValue(); 95 break; 96 case HSSFCell.CELL_TYPE_NUMERIC: 97 strCell = String.valueOf(cell.getNumericCellValue()); 98 break; 99 case HSSFCell.CELL_TYPE_BOOLEAN: 100 strCell = String.valueOf(cell.getBooleanCellValue()); 101 break; 102 case HSSFCell.CELL_TYPE_BLANK: 103 strCell = ""; 104 break; 105 default: 106 strCell = ""; 107 break; 108 } 109 if (strCell.equals("") || strCell == null) { 110 return ""; 111 } 112 if (cell == null) { 113 return ""; 114 } 115 return strCell; 116 } 117 118 /** 119 * 获取单元格数据内容为日期类型的数据 120 * 121 * @param cell 122 * Excel单元格 123 * @return String 单元格数据内容 124 */ 125 private String getDateCellValue(HSSFCell cell) { 126 String result = ""; 127 try { 128 int cellType = cell.getCellType(); 129 if (cellType == HSSFCell.CELL_TYPE_NUMERIC) { 130 Date date = cell.getDateCellValue(); 131 result = (date.getYear() + 1900) + "-" + (date.getMonth() + 1) 132 + "-" + date.getDate(); 133 } else if (cellType == HSSFCell.CELL_TYPE_STRING) { 134 String date = getStringCellValue(cell); 135 result = date.replaceAll("[年月]", "-").replace("日", "").trim(); 136 } else if (cellType == HSSFCell.CELL_TYPE_BLANK) { 137 result = ""; 138 } 139 } catch (Exception e) { 140 System.out.println("日期格式不正确!"); 141 e.printStackTrace(); 142 } 143 return result; 144 } 145 146 /** 147 * 根据HSSFCell类型设置数据 148 * @param cell 149 * @return 150 */ 151 private String getCellFormatValue(HSSFCell cell) { 152 String cellvalue = ""; 153 if (cell != null) { 154 // 判断当前Cell的Type 155 switch (cell.getCellType()) { 156 // 如果当前Cell的Type为NUMERIC 157 case HSSFCell.CELL_TYPE_NUMERIC: 158 case HSSFCell.CELL_TYPE_FORMULA: { 159 // 判断当前的cell是否为Date 160 if (HSSFDateUtil.isCellDateFormatted(cell)) { 161 Date date = cell.getDateCellValue(); 162 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 163 cellvalue = sdf.format(date); 164 } 165 // 如果是纯数字 166 else { 167 // 取得当前Cell的数值 168 cellvalue = String.valueOf(cell.getNumericCellValue()); 169 } 170 break; 171 } 172 // 如果当前Cell的Type为STRIN 173 case HSSFCell.CELL_TYPE_STRING: 174 // 取得当前的Cell字符串 175 cellvalue = cell.getRichStringCellValue().getString(); 176 break; 177 // 默认的Cell值 178 default: 179 cellvalue = " "; 180 } 181 } else { 182 cellvalue = ""; 183 } 184 return cellvalue; 185 186 } 187 188 public static void main(String[] args) { 189 try { 190 // 对读取Excel表格标题测试 191 InputStream is = new FileInputStream("d:\\test2.xls"); 192 ImportExcel excelReader = new ImportExcel(); 193 String[] title = excelReader.readExcelTitle(is); 194 System.out.println("获得Excel表格的标题:"); 195 for (String s : title) { 196 System.out.print(s + " "); 197 } 198 System.out.println(); 199 200 // 对读取Excel表格内容测试 201 InputStream is2 = new FileInputStream("d:\\test2.xls"); 202 Map map = excelReader.readExcelContent(is2); 203 System.out.println("获得Excel表格的内容:"); 204 //这里由于xls合并了单元格需要对索引特殊处理 205 for (int i = 2; i <= map.size()+1; i++) { 206 System.out.println(map.get(i)); 207 } 208 209 } catch (FileNotFoundException e) { 210 System.out.println("未找到指定路径的文件!"); 211 e.printStackTrace(); 212 } 213 } 214 215 }
将Excel中的数据通过后台程序维护到一个Map集合中,再利用String的split方法以“-”进行分割,得到单个的值,如果想要将这批数据插入到数据库,则去实例化对象的dto,再给dto对应属性赋值,最终写sql再insert到表中。
Excel导出工具类的实现:
1 import org.apache.poi.hssf.usermodel.*; 2 import org.apache.poi.hssf.util.HSSFColor; 3 import org.apache.poi.ss.usermodel.IndexedColors; 4 import org.apache.poi.ss.util.CellRangeAddress; 5 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 import java.io.IOException; 9 import java.io.OutputStream; 10 import java.util.ArrayList; 11 import java.util.List; 12 13 /** 14 * @author [email protected] 15 * @version 1.0 16 * @name 17 * @description 18 * @date 2017/10/19 19 */ 20 public class ExportExcel { 21 22 /** 23 * 显示的导出表的标题 24 */ 25 private String title; 26 27 /** 28 * 导出表的列名 29 */ 30 private String[] columnName; 31 32 /** 33 * 需要导出的数据集合 34 */ 35 private List
用于测试导出的Servlet程序:
1 import javax.servlet.ServletException; 2 import javax.servlet.annotation.WebServlet; 3 import javax.servlet.http.HttpServlet; 4 import javax.servlet.http.HttpServletRequest; 5 import javax.servlet.http.HttpServletResponse; 6 import java.io.IOException; 7 import java.util.ArrayList; 8 import java.util.List; 9 10 /** 11 * @author [email protected] 12 * @version 1.0 13 * @name 14 * @description 15 * @date 2017/10/19 16 */ 17 @WebServlet(name = "TestServlet") 18 public class TestServlet extends HttpServlet { 19 @Override 20 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 21 String title = "货运单据导出"; 22 String[] columnName = new String[]{"序号","num1","num2"}; 23 ListdataList = new ArrayList (); 24 Object[] objs; 25 for (int i = 0; i <2; i++) { 26 objs = new Object[columnName.length]; 27 objs[0] = i; 28 objs[1] = "1"; 29 objs[2] = "2"; 30 dataList.add(objs); 31 } 32 //实例化工具类 33 ExportExcel ex = new ExportExcel(title, columnName, dataList,request,response); 34 try { 35 //导出excel 36 ex.export(); 37 } catch (Exception e) { 38 e.printStackTrace(); 39 } 40 } 41 42 @Override 43 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 44 doPost(request,response); 45 } 46 }