pom.xml依赖:

  1. <dependency>
  2. <groupId>org.apache.poi</groupId>
  3. <artifactId>poi</artifactId>
  4. <version>3.17</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.poi</groupId>
  8. <artifactId>poi-scratchpad</artifactId>
  9. <version>3.17</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.apache.poi</groupId>
  13. <artifactId>poi-ooxml</artifactId>
  14. <version>3.17</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.apache.poi</groupId>
  18. <artifactId>poi-ooxml-schemas</artifactId>
  19. <version>3.17</version>
  20. </dependency>
  21. <dependency>
  22. <groupId>com.google.guava</groupId>
  23. <artifactId>guava</artifactId>
  24. <version>23.0</version>
  25. </dependency>

Java类ExcelUtils代码:

  1. package com.dzpykj.files.excel;
  2.  
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.OutputStream;
  8. import java.text.SimpleDateFormat;
  9. import java.util.Calendar;
  10. import java.util.Date;
  11. import java.util.Iterator;
  12. import java.util.List;
  13. import java.util.Map;
  14.  
  15. import org.apache.commons.lang3.StringUtils;
  16. import org.apache.poi.EncryptedDocumentException;
  17. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  18. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  19. import org.apache.poi.ss.usermodel.BorderStyle;
  20. import org.apache.poi.ss.usermodel.Cell;
  21. import org.apache.poi.ss.usermodel.CellStyle;
  22. import org.apache.poi.ss.usermodel.CellType;
  23. import org.apache.poi.ss.usermodel.FillPatternType;
  24. import org.apache.poi.ss.usermodel.Font;
  25. import org.apache.poi.ss.usermodel.HorizontalAlignment;
  26. import org.apache.poi.ss.usermodel.IndexedColors;
  27. import org.apache.poi.ss.usermodel.Row;
  28. import org.apache.poi.ss.usermodel.Sheet;
  29. import org.apache.poi.ss.usermodel.VerticalAlignment;
  30. import org.apache.poi.ss.usermodel.Workbook;
  31. import org.apache.poi.ss.usermodel.WorkbookFactory;
  32. import org.apache.poi.xssf.usermodel.XSSFCellStyle;
  33. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  34.  
  35. import com.google.common.collect.Maps;
  36.  
  37. /**
  38. * Excel操作工具类
  39. * @author ChaiXY
  40. */
  41. public class ExcelUtils {
  42.  
  43. // @Value("${file_base_path}")
  44. // private static String fileBasePath;//文件的基础路径
  45. // private static String fileBasePath = System.getProperty("user.dir") + File.separator + "excel" + File.separator;;//文件的基础路径
  46.  
  47. public static final String OFFICE_EXCEL_XLS = "xls";
  48. public static final String OFFICE_EXCEL_XLSX = "xlsx";
  49.  
  50. /**
  51. * 读取指定Sheet也的内容
  52. * @param filepath filepath 文件全路径
  53. * @param sheetNo sheet序号,从0开始,如果读取全文sheetNo设置null
  54. */
  55. public static String readExcel(String filepath, Integer sheetNo)
  56. throws EncryptedDocumentException, InvalidFormatException, IOException {
  57. StringBuilder sb = new StringBuilder();
  58. Workbook workbook = getWorkbook(filepath);
  59. if (workbook != null) {
  60. if (sheetNo == null) {
  61. int numberOfSheets = workbook.getNumberOfSheets();
  62. for (int i = 0; i < numberOfSheets; i++) {
  63. Sheet sheet = workbook.getSheetAt(i);
  64. if (sheet == null) {
  65. continue;
  66. }
  67. sb.append(readExcelSheet(sheet));
  68. }
  69. } else {
  70. Sheet sheet = workbook.getSheetAt(sheetNo);
  71. if (sheet != null) {
  72. sb.append(readExcelSheet(sheet));
  73. }
  74. }
  75. }
  76. return sb.toString();
  77. }
  78.  
  79. /**
  80. * 根据文件路径获取Workbook对象
  81. * @param filepath 文件全路径
  82. */
  83. public static Workbook getWorkbook(String filepath)
  84. throws EncryptedDocumentException, InvalidFormatException, IOException {
  85. InputStream is = null;
  86. Workbook wb = null;
  87. if (StringUtils.isBlank(filepath)) {
  88. throw new IllegalArgumentException("文件路径不能为空");
  89. } else {
  90. String suffiex = getSuffiex(filepath);
  91. if (StringUtils.isBlank(suffiex)) {
  92. throw new IllegalArgumentException("文件后缀不能为空");
  93. }
  94. if (OFFICE_EXCEL_XLS.equals(suffiex) || OFFICE_EXCEL_XLSX.equals(suffiex)) {
  95. try {
  96. is = new FileInputStream(filepath);
  97. wb = WorkbookFactory.create(is);
  98. } finally {
  99. if (is != null) {
  100. is.close();
  101. }
  102. if (wb != null) {
  103. wb.close();
  104. }
  105. }
  106. } else {
  107. throw new IllegalArgumentException("该文件非Excel文件");
  108. }
  109. }
  110. return wb;
  111. }
  112.  
  113. /**
  114. * 获取后缀
  115. * @param filepath filepath 文件全路径
  116. */
  117. private static String getSuffiex(String filepath) {
  118. if (StringUtils.isBlank(filepath)) {
  119. return "";
  120. }
  121. int index = filepath.lastIndexOf(".");
  122. if (index == -1) {
  123. return "";
  124. }
  125. return filepath.substring(index + 1, filepath.length());
  126. }
  127.  
  128. private static String readExcelSheet(Sheet sheet) {
  129. StringBuilder sb = new StringBuilder();
  130.  
  131. if(sheet != null){
  132. int rowNos = sheet.getLastRowNum();// 得到excel的总记录条数
  133. for (int i = 0; i <= rowNos; i++) {// 遍历行
  134. Row row = sheet.getRow(i);
  135. if(row != null){
  136. int columNos = row.getLastCellNum();// 表头总共的列数
  137. for (int j = 0; j < columNos; j++) {
  138. Cell cell = row.getCell(j);
  139. if(cell != null){
  140. cell.setCellType(CellType.STRING);
  141. sb.append(cell.getStringCellValue() + " ");
  142. // System.out.print(cell.getStringCellValue() + " ");
  143. }
  144. }
  145. // System.out.println();
  146. }
  147. }
  148. }
  149.  
  150. return sb.toString();
  151. }
  152.  
  153. /**
  154. * 读取指定Sheet页的表头
  155. * @param filepath filepath 文件全路径
  156. * @param sheetNo sheet序号,从0开始,必填
  157. */
  158. public static Row readTitle(String filepath, int sheetNo)
  159. throws IOException, EncryptedDocumentException, InvalidFormatException {
  160. Row returnRow = null;
  161. Workbook workbook = getWorkbook(filepath);
  162. if (workbook != null) {
  163. Sheet sheet = workbook.getSheetAt(sheetNo);
  164. returnRow = readTitle(sheet);
  165. }
  166. return returnRow;
  167. }
  168.  
  169. /**
  170. * 读取指定Sheet页的表头
  171. */
  172. public static Row readTitle(Sheet sheet) throws IOException {
  173. Row returnRow = null;
  174. int totalRow = sheet.getLastRowNum();// 得到excel的总记录条数
  175. for (int i = 0; i < totalRow; i++) {// 遍历行
  176. Row row = sheet.getRow(i);
  177. if (row == null) {
  178. continue;
  179. }
  180. returnRow = sheet.getRow(0);
  181. break;
  182. }
  183. return returnRow;
  184. }
  185.  
  186. /**
  187. * 创建Excel文件
  188. * @param filepath filepath 文件全路径
  189. * @param sheetName 新Sheet页的名字
  190. * @param titles 表头
  191. * @param values 每行的单元格
  192. */
  193. public static boolean writeExcel(String filepath, String sheetName, List<String> titles,
  194. List<Map<String, Object>> values) throws IOException {
  195. boolean success = false;
  196. OutputStream outputStream = null;
  197. if (StringUtils.isBlank(filepath)) {
  198. throw new IllegalArgumentException("文件路径不能为空");
  199. } else {
  200. String suffiex = getSuffiex(filepath);
  201. if (StringUtils.isBlank(suffiex)) {
  202. throw new IllegalArgumentException("文件后缀不能为空");
  203. }
  204. Workbook workbook;
  205. if ("xls".equals(suffiex.toLowerCase())) {
  206. workbook = new HSSFWorkbook();
  207. } else {
  208. workbook = new XSSFWorkbook();
  209. }
  210. // 生成一个表格
  211. Sheet sheet;
  212. if (StringUtils.isBlank(sheetName)) {
  213. // name 为空则使用默认值
  214. sheet = workbook.createSheet();
  215. } else {
  216. sheet = workbook.createSheet(sheetName);
  217. }
  218. // 设置表格默认列宽度为15个字节
  219. sheet.setDefaultColumnWidth((short) 15);
  220. // 生成样式
  221. Map<String, CellStyle> styles = createStyles(workbook);
  222. // 创建标题行
  223. Row row = sheet.createRow(0);
  224. // 存储标题在Excel文件中的序号
  225. Map<String, Integer> titleOrder = Maps.newHashMap();
  226. for (int i = 0; i < titles.size(); i++) {
  227. Cell cell = row.createCell(i);
  228. cell.setCellStyle(styles.get("header"));
  229. String title = titles.get(i);
  230. cell.setCellValue(title);
  231. titleOrder.put(title, i);
  232. }
  233. // 写入正文
  234. Iterator<Map<String, Object>> iterator = values.iterator();
  235. // 行号
  236. int index = 1;
  237. while (iterator.hasNext()) {
  238. row = sheet.createRow(index);
  239. Map<String, Object> value = iterator.next();
  240. for (Map.Entry<String, Object> map : value.entrySet()) {
  241. // 获取列名
  242. String title = map.getKey();
  243. // 根据列名获取序号
  244. int i = titleOrder.get(title);
  245. // 在指定序号处创建cell
  246. Cell cell = row.createCell(i);
  247. // 设置cell的样式
  248. if (index % 2 == 1) {
  249. cell.setCellStyle(styles.get("cellA"));
  250. } else {
  251. cell.setCellStyle(styles.get("cellB"));
  252. }
  253. // 获取列的值
  254. Object object = map.getValue();
  255. // 判断object的类型
  256. SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  257. if (object instanceof Double) {
  258. cell.setCellValue((Double) object);
  259. } else if (object instanceof Date) {
  260. String time = simpleDateFormat.format((Date) object);
  261. cell.setCellValue(time);
  262. } else if (object instanceof Calendar) {
  263. Calendar calendar = (Calendar) object;
  264. String time = simpleDateFormat.format(calendar.getTime());
  265. cell.setCellValue(time);
  266. } else if (object instanceof Boolean) {
  267. cell.setCellValue((Boolean) object);
  268. } else {
  269. if (object != null) {
  270. cell.setCellValue(object.toString());
  271. }
  272. }
  273. }
  274. index++;
  275. }
  276.  
  277. try {
  278. outputStream = new FileOutputStream(filepath);
  279. workbook.write(outputStream);
  280. success = true;
  281. } finally {
  282. if (outputStream != null) {
  283. outputStream.close();
  284. }
  285. if (workbook != null) {
  286. workbook.close();
  287. }
  288. }
  289. return success;
  290. }
  291. }
  292.  
  293. /**
  294. * 设置格式
  295. */
  296. private static Map<String, CellStyle> createStyles(Workbook wb) {
  297. Map<String, CellStyle> styles = Maps.newHashMap();
  298.  
  299. // 标题样式
  300. XSSFCellStyle titleStyle = (XSSFCellStyle) wb.createCellStyle();
  301. titleStyle.setAlignment(HorizontalAlignment.CENTER); // 水平对齐
  302. titleStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直对齐
  303. titleStyle.setLocked(true); // 样式锁定
  304. titleStyle.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex());
  305. Font titleFont = wb.createFont();
  306. titleFont.setFontHeightInPoints((short) 16);
  307. titleFont.setBold(true);
  308. titleFont.setFontName("微软雅黑");
  309. titleStyle.setFont(titleFont);
  310. styles.put("title", titleStyle);
  311.  
  312. // 文件头样式
  313. XSSFCellStyle headerStyle = (XSSFCellStyle) wb.createCellStyle();
  314. headerStyle.setAlignment(HorizontalAlignment.CENTER);
  315. headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
  316. headerStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex()); // 前景色
  317. headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 颜色填充方式
  318. headerStyle.setWrapText(true);
  319. headerStyle.setBorderRight(BorderStyle.THIN); // 设置边界
  320. headerStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
  321. headerStyle.setBorderLeft(BorderStyle.THIN);
  322. headerStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
  323. headerStyle.setBorderTop(BorderStyle.THIN);
  324. headerStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
  325. headerStyle.setBorderBottom(BorderStyle.THIN);
  326. headerStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
  327. Font headerFont = wb.createFont();
  328. headerFont.setFontHeightInPoints((short) 12);
  329. headerFont.setColor(IndexedColors.WHITE.getIndex());
  330. titleFont.setFontName("微软雅黑");
  331. headerStyle.setFont(headerFont);
  332. styles.put("header", headerStyle);
  333.  
  334. Font cellStyleFont = wb.createFont();
  335. cellStyleFont.setFontHeightInPoints((short) 12);
  336. cellStyleFont.setColor(IndexedColors.BLUE_GREY.getIndex());
  337. cellStyleFont.setFontName("微软雅黑");
  338.  
  339. // 正文样式A
  340. XSSFCellStyle cellStyleA = (XSSFCellStyle) wb.createCellStyle();
  341. cellStyleA.setAlignment(HorizontalAlignment.CENTER); // 居中设置
  342. cellStyleA.setVerticalAlignment(VerticalAlignment.CENTER);
  343. cellStyleA.setWrapText(true);
  344. cellStyleA.setBorderRight(BorderStyle.THIN);
  345. cellStyleA.setRightBorderColor(IndexedColors.BLACK.getIndex());
  346. cellStyleA.setBorderLeft(BorderStyle.THIN);
  347. cellStyleA.setLeftBorderColor(IndexedColors.BLACK.getIndex());
  348. cellStyleA.setBorderTop(BorderStyle.THIN);
  349. cellStyleA.setTopBorderColor(IndexedColors.BLACK.getIndex());
  350. cellStyleA.setBorderBottom(BorderStyle.THIN);
  351. cellStyleA.setBottomBorderColor(IndexedColors.BLACK.getIndex());
  352. cellStyleA.setFont(cellStyleFont);
  353. styles.put("cellA", cellStyleA);
  354.  
  355. // 正文样式B:添加前景色为浅黄色
  356. XSSFCellStyle cellStyleB = (XSSFCellStyle) wb.createCellStyle();
  357. cellStyleB.setAlignment(HorizontalAlignment.CENTER);
  358. cellStyleB.setVerticalAlignment(VerticalAlignment.CENTER);
  359. cellStyleB.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex());
  360. cellStyleB.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  361. cellStyleB.setWrapText(true);
  362. cellStyleB.setBorderRight(BorderStyle.THIN);
  363. cellStyleB.setRightBorderColor(IndexedColors.BLACK.getIndex());
  364. cellStyleB.setBorderLeft(BorderStyle.THIN);
  365. cellStyleB.setLeftBorderColor(IndexedColors.BLACK.getIndex());
  366. cellStyleB.setBorderTop(BorderStyle.THIN);
  367. cellStyleB.setTopBorderColor(IndexedColors.BLACK.getIndex());
  368. cellStyleB.setBorderBottom(BorderStyle.THIN);
  369. cellStyleB.setBottomBorderColor(IndexedColors.BLACK.getIndex());
  370. cellStyleB.setFont(cellStyleFont);
  371. styles.put("cellB", cellStyleB);
  372.  
  373. return styles;
  374. }
  375.  
  376. /**
  377. * 将源文件的内容复制到新Excel文件(可供理解Excel使用,使用价值不大)
  378. * @param srcFilepath 源文件全路径
  379. * @param desFilepath 目标文件全路径
  380. */
  381. public static void writeExcel(String srcFilepath, String desFilepath)
  382. throws IOException, EncryptedDocumentException, InvalidFormatException {
  383. FileOutputStream outputStream = null;
  384. String suffiex = getSuffiex(desFilepath);
  385. if (StringUtils.isBlank(suffiex)) {
  386. throw new IllegalArgumentException("文件后缀不能为空");
  387. }
  388. Workbook workbook_des;
  389. if ("xls".equals(suffiex.toLowerCase())) {
  390. workbook_des = new HSSFWorkbook();
  391. } else {
  392. workbook_des = new XSSFWorkbook();
  393. }
  394.  
  395. Workbook workbook = getWorkbook(srcFilepath);
  396. if (workbook != null) {
  397. int numberOfSheets = workbook.getNumberOfSheets();
  398. for (int k = 0; k < numberOfSheets; k++) {
  399. Sheet sheet = workbook.getSheetAt(k);
  400. Sheet sheet_des = workbook_des.createSheet(sheet.getSheetName());
  401. if (sheet != null) {
  402. int rowNos = sheet.getLastRowNum();
  403. for (int i = 0; i <= rowNos; i++) {
  404. Row row = sheet.getRow(i);
  405. Row row_des = sheet_des.createRow(i);
  406. if(row != null){
  407. int columNos = row.getLastCellNum();
  408. for (int j = 0; j < columNos; j++) {
  409. Cell cell = row.getCell(j);
  410. Cell cell_des = row_des.createCell(j);
  411. if(cell != null){
  412. cell.setCellType(CellType.STRING);
  413. cell_des.setCellType(CellType.STRING);
  414.  
  415. cell_des.setCellValue(cell.getStringCellValue());
  416. }
  417. }
  418. }
  419. }
  420. }
  421.  
  422. }
  423. }
  424.  
  425. try {
  426. outputStream = new FileOutputStream(desFilepath);
  427. workbook_des.write(outputStream);
  428. } finally {
  429. if (outputStream != null) {
  430. outputStream.close();
  431. }
  432. if (workbook != null) {
  433. workbook_des.close();
  434. }
  435. }
  436. }
  437.  
  438. public static void main(String[] args) {
  439.  
  440. }
  441. }

Java POI 操作Excel(读取/写入)的更多相关文章

  1. java poi操作excel 添加 锁定单元格保护

    Excel的book保护是很常用的,主要是不想让别人修改Excel的时候用.这样能够避免恶意随便修改数据,提高数据的可信度. 下面介绍JAVA POI来实现设置book保护: 使用HSSFSheet类 ...

  2. java poi操作excel示例代码

    import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io ...

  3. java poi 操作

    Java POI 操作Excel(读取/写入) https://www.cnblogs.com/dzpykj/p/8417738.html Java操作Excel之Poi基本操作 https://my ...

  4. JAVA的POI操作Excel

    1.1Excel简介 一个excel文件就是一个工作簿workbook,一个工作簿中可以创建多张工作表sheet,而一个工作表中包含多个单元格Cell,这些单元格都是由列(Column)行(Row)组 ...

  5. java使用POI操作excel文件,实现批量导出,和导入

    一.POI的定义 JAVA中操作Excel的有两种比较主流的工具包: JXL 和 POI .jxl 只能操作Excel 95, 97, 2000也即以.xls为后缀的excel.而poi可以操作Exc ...

  6. java里poi操作excel的工具类(兼容各版本)

    转: java里poi操作excel的工具类(兼容各版本) 下面是文件内具体内容,文件下载: import java.io.FileNotFoundException; import java.io. ...

  7. 使用POI操作Excel时对事先写入模板的公式强制执行

    场景:POI读取Excel模板. 当使用POI操作Excel时,发现由POI生成的公式能够在打开Excel是被执行, 而事先手工写入Excel模板文件的公式则不自动被调用,必须手动双击该Cell才能生 ...

  8. java 使用jxl poi 操作excel

    java操作excel  创建.修改 xls 文件 JAVA操作Excel文件 Java生成和操作Excel文件 java导出Excel通用方法 Java 实现导出excel表 POI Java PO ...

  9. Java POI操作Excel注意点

    excel的行索引和列索引都是从0开始,而行号和列号都是从1开始 POI·操作excel基本上都是使用索引 XSSFRow对象的 row.getLastCellNum() 方法返回的是当前行最后有效列 ...

随机推荐

  1. Codeforces Round #397 by Kaspersky Lab and Barcelona Bootcamp (Div. 1 + Div. 2 combined) A

    Description There are literally dozens of snooker competitions held each year, and team Jinotega tri ...

  2. jQuery val()方法及valHooks源码解读

    val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) {//无参数 ...

  3. 如何在spring环境中做单元测试

    在测试类的上方加入以下注解 @RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:spring.xm ...

  4. mongodb 上限集合

    上限集合是固定大小的循环集合按照插入以支持高性能的创建,读取和删除操作.通过循环,这意味着,当分配给该集合中的固定大小要用尽时,它会开始删除集合中最旧的文件而不提供任何明确的命令. 上限集合限制更新, ...

  5. vue2.0:(二)、mock数据

    什么是mock数据呢?很多情况下,后台的搭建比起前端来说要麻烦的多,所以,常常是前端写好了页面以后后台接口却没有写好,但是在一个项目中,接口调试确实是最浪费时间的,所以,往往前端需要自己模拟数据. 第 ...

  6. 事件冒泡之cancelBubble和stoppropagation的区别

    事实上stoppropagation和cancelBubble的作用是一样的,都是用来阻止浏览器默认的事件冒泡行为. 不同之处在于stoppropagation属于W3C标准,试用于Firefox等浏 ...

  7. mybatis实现使用原生的sql

    1.相应的xml文件中 <select id="selectByCategories" resultType="map" parameterType=&q ...

  8. Monkey安装和使用介绍

    安装步骤1)安装sdk环境在系统环境变量中配置 ANDROID_HOMED:\sdk PATH%ANDROID_HOME%\tools;%ANDROID_HOME%\platform-tools;%A ...

  9. 精仿百思不得姐客户端应用iOS源码

    XFBaiSiBuDeJie 高仿百思不得姐客户端 初次学习使用RAC,还不是怎么熟悉,使用的仍是MVC模式,MVVM还在摸索中... 如果大家觉得还不错,请给颗星星支持下~~~ 程序中使用到的库 A ...

  10. Asp.Net Core 入门(十)—— 模型绑定和验证

    模型绑定时将Http请求中的数据映射到控制器操作方法上对应的参数,操作方法中的参数可以是简单类型,如整形,字符串等,也可以是复杂类型,如Product,Order等. Asp.Net Core MVC ...