java excel 导入demo_Java——excel导入导出demo

1. java导入

package xx;

import org.apache.poi.hssf.usermodel.HSSFCell;

import org.apache.poi.hssf.usermodel.HSSFDataFormat;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.CellStyle;

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 java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.text.DecimalFormat;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Date;

import java.util.List;

/**

* @author CaptainFM

* @date 2019/7/2 0002 9:55

* 读取 excel表格,兼容2003和2007

*/

public class D {

/** 总行数 */

private int totalRows = 0;

/** 总列数 */

private int totalCells = 0;

/** 错误信息 */

private String errorInfo;

/** 构造方法 */

public D() {}

/**

* 得到总行数

*/

public int getTotalRows() {

return totalRows;

}

/**

* 得到总列数

*/

public int getTotalCells() {

return totalCells;

}

/**

* 得到错误信息

*/

public String getErrorInfo() {

return errorInfo;

}

/**

*

* 验证excel文件

* @author CaptainFM

* @param:filePath 文件完整路径

* @return 返回 true 表示文件没有问题

*/

public boolean validateExcel(String filePath) {

// 检查文件名是否为空或者是否是Excel格式的文件

if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {

errorInfo = "文件不是excel格式";

return false;

}

// 检查文件是否存在

File file = new File(filePath);

if (file == null || !file.exists()) {

errorInfo = "文件不存在";

return false;

}

return true;

}

/**

* 根据文件名读取excel文件

* @author CaptainFM

* @param filePath 文件完整路径

* @param ignoreRows 读取数据忽略的行数,比喻第一行不需要读入,忽略的行数为1

* @return:List 最后读取的结果,数据结构:List>

*/

public List> read(String filePath, int ignoreRows) {

List> dataList = new ArrayList>();

InputStream is = null;

try {

// 验证文件是否合法

if (!validateExcel(filePath)) {

System.out.println(errorInfo);

return null;

}

// 判断文件的类型,是2003还是2007

boolean isExcel2003 = true;

if (isExcel2007(filePath)) {

isExcel2003 = false;

}

// 调用本类提供的根据流读取的方法

File file = new File(filePath);

is = new FileInputStream(file);

dataList = read(is, isExcel2003, ignoreRows);

is.close();

} catch (Exception ex) {

ex.printStackTrace();

} finally {

if (is != null) {

try {

is.close();

} catch (IOException e) {

is = null;

e.printStackTrace();

}

}

}

// 返回最后读取的结果

return dataList;

}

/**

* 根据流读取Excel文件

* @author CaptainFM

* @param inputStream

* @param isExcel2003 是否是2003的表格(xls格式)

* @param ignoreRows 读取数据忽略的行数,比喻第一行不需要读入,忽略的行数为1

* @return:List

*/

public List> read(InputStream inputStream, boolean isExcel2003, int ignoreRows) {

List> dataList = null;

try {

// 根据版本选择创建Workbook的方式

Workbook wb = null;

if (isExcel2003) {

wb = new HSSFWorkbook(inputStream);

} else {

wb = new XSSFWorkbook(inputStream);

}

dataList = read(wb, ignoreRows);

} catch (IOException e) {

e.printStackTrace();

}

return dataList;

}

/**

* 读取数据

* @author CaptainFM

* @param ignoreRows 读取数据忽略的行数,比喻第一行不需要读入,忽略的行数为1

* @reture:List>

*/

private List> read(Workbook wb, int ignoreRows) {

List> dataList = new ArrayList>();

// 得到第一个shell

Sheet sheet = wb.getSheetAt(0);

// 得到Excel的行数

this.totalRows = sheet.getPhysicalNumberOfRows();

// 得到Excel的列数,不从表格的第一行得到列数,从忽略之后的,要读取的第一行 获取列数

if (this.totalRows >= 1 && sheet.getRow(ignoreRows) != null) {

this.totalCells = sheet.getRow(ignoreRows).getPhysicalNumberOfCells();

}

// 循环Excel的行,不从表格的第一行循环,去掉忽略的行数

for (int r = ignoreRows; r < this.totalRows; r++) {

Row row = sheet.getRow(r);

if (row == null) {

continue;

}

List rowList = new ArrayList();

// 循环Excel的列

for (int c = 0; c <= this.getTotalCells(); c++) {

Cell cell = row.getCell(c);

String cellValue = "";

if (null != cell) {

// 以下是判断数据的类型

switch (cell.getCellType()) {

case HSSFCell.CELL_TYPE_NUMERIC: // 数字

// 如果数字是日期类型,就转换成日期

if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式

SimpleDateFormat sdf = null;

if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) {

sdf = new SimpleDateFormat("HH:mm");

} else {// 日期

sdf = new SimpleDateFormat("yyyy年MM月dd日");

}

Date date = cell.getDateCellValue();

cellValue = sdf.format(date);

} else if (cell.getCellStyle().getDataFormat() == 31) {

// 处理自定义日期格式:yyyy年m月d日(通过判断单元格的格式id解决,id的值是31)

SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");

double value = cell.getNumericCellValue();

Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value);

cellValue = sdf.format(date);

} else {

double value = cell.getNumericCellValue();

CellStyle style = cell.getCellStyle();

DecimalFormat format = new DecimalFormat();

String temp = style.getDataFormatString();

// 单元格设置成常规

if (temp.equals("General")) {

format.applyPattern("#");

}

cellValue = format.format(value);

}

break;

case HSSFCell.CELL_TYPE_STRING: // 字符串

cellValue = cell.getStringCellValue();

break;

case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean

cellValue = cell.getBooleanCellValue() + "";

break;

case HSSFCell.CELL_TYPE_FORMULA: // 公式

cellValue = cell.getCellFormula() + "";

break;

case HSSFCell.CELL_TYPE_BLANK: // 空值

cellValue = "";

break;

case HSSFCell.CELL_TYPE_ERROR: // 故障

cellValue = "非法字符";

break;

default:

cellValue = "未知类型";

break;

}

}

rowList.add(cellValue);

}

// 保存第r行的第c列

dataList.add(rowList);

}

return dataList;

}

/**

* 是否是2003的excel,返回true是2003

* @author CaptainFM

* @param filePath 文件完整路径

* @return boolean true代表是2003

*/

public static boolean isExcel2003(String filePath) {

return filePath.matches("^.+\\.(?i)(xls)$");

}

/**

* 是否是2007的excel,返回true是2007

* @author CaptainFM

* @param filePath 文件完整路径

* @return boolean true代表是2007

*/

public static boolean isExcel2007(String filePath) {

return filePath.matches("^.+\\.(?i)(xlsx)$");

}

}

package xx;

import java.util.List;

/**

* @author CaptainFM

* @date 2019/7/3 0003 10:07

* 测试类

*/

public class D1 {

public static void main(String[] args) throws Exception {

D re = new D();

List> list = re.read("C:/Users/Administrator/Desktop/社保公积金薪酬字段.xlsx", 1);//忽略前1行

// 遍历读取结果

if (list != null) {

for (int i = 0; i < list.size(); i++) {

System.out.print("第" + (1+i) + "行");

List cellList = list.get(i);

for (int j = 0; j < cellList.size(); j++) {

System.out.print(" 第" + (j + 1) + "列值:");

System.out.print(" " + cellList.get(j));

}

System.out.println();

}

}

}

}

2. java导出

package xx;

import org.apache.commons.io.FileUtils;

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.xssf.usermodel.XSSFWorkbook;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

/**

* @author CaptainFM

* @date 2019/6/25 0025 15:39

*/

//导出工作表

public class C {

public static void main(String args[]){

String[] title = {"id","name","sex"};

//创建Excel工作簿

XSSFWorkbook workbook = new XSSFWorkbook();

//创建一个工作表sheet

Sheet sheet = workbook.createSheet();

//创建第一行

Row row = sheet.createRow(0);

Cell cell = null;

//插入第一行数据 id,name,sex

for (int i = 0; i < title.length; i++) {

cell = row.createCell(i);

cell.setCellValue(title[i]);

}

//追加数据

for (int i = 1; i <= 10; i++) {

Row nextrow = sheet.createRow(i);

Cell cell2 = nextrow.createCell(0);

cell2.setCellValue("a" + i);

cell2 = nextrow.createCell(1);

cell2.setCellValue("user" + i);

cell2 = nextrow.createCell(2);

cell2.setCellValue("男");

}

//需要解析的Excel文件

File file=new File("C:/Users/Administrator/Desktop/社保公积金薪酬字段.xlsx");

try {

file.createNewFile();

//将Excel内容存盘

FileOutputStream stream = FileUtils.openOutputStream(file);

workbook.write(stream);

stream.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值