- 使用jar包
org.apache.poi poi-ooxml 3.14
此处演示导出手机号码 并导出sql 脚本
- 贴入代码
@SuppressWarnings("static-access")
public static void main(String[] args) {
MyUtilC myUtilC = new MyUtilC();
String filePath = "要读取的Excel路径";
XSSFWorkbook wookbook = null;
try {
wookbook = new XSSFWorkbook(new FileInputStream(filePath));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
XSSFSheet sheet = wookbook.getSheet("表头");
// 获取到Excel文件中的所有行数
int rows = sheet.getPhysicalNumberOfRows();
// 遍历行
try {
for (int i = 0; i < rows; i++) {
// 读取左上端单元格
XSSFRow row = sheet.getRow(i);
// 行不为空
if (row != null) {
// 获取到Excel文件中的所有的列
// int cells = row.getPhysicalNumberOfCells();
// 读取手机号数据
XSSFCell nameCell = row.getCell(2);
String mobile = myUtilC.getValue(nameCell);
//简单演示一下
String sql = "select * from t_user where mobile = '"+mobile +"';";
boolean add = true;
myUtilC.add("sql脚本写出路径", sql, add);
//此处只为换行 与上方路径保持一致
myUtilC.add("sql脚本写出路径", "\n", add);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("写入成功");
}
@SuppressWarnings("static-access")
private String getValue(XSSFCell xSSFCell) {
if (null == xSSFCell) {
return "";
}
if (xSSFCell.getCellType() == xSSFCell.CELL_TYPE_BOOLEAN) {
// 返回布尔类型
return String.valueOf(xSSFCell.getBooleanCellValue());
} else if (xSSFCell.getCellType() == xSSFCell.CELL_TYPE_NUMERIC) {
// 返回数值类型
//此处注意 读出的手机号码数据 为 1.36****E** 用下方if代码矫正 即可恢复正常
if (String.valueOf(xSSFCell.getNumericCellValue()).indexOf("E") == -1) {
return String.valueOf(xSSFCell.getNumericCellValue());
} else {
return new DecimalFormat("#").format(xSSFCell.getNumericCellValue());
}
} else {
// 返回字符串类型
return String.valueOf(xSSFCell.getStringCellValue());
}
}
//此处为文件写出
@SuppressWarnings("resource")
public static String add(String address, String message, boolean add) throws Exception {
// 创建输出流对象
// 创建一个向具有指定 name 的文件中写入数据的输出文件流。如果第二个参数为 true,则将字节写入文件末尾处,而不是写入文件开始处。
String ret = "";
FileOutputStream fos = null;
try {
fos = new FileOutputStream(address, add);
} catch (FileNotFoundException e) {
throw new Exception(e.getMessage());
}
// 写出数据
try {
fos.write((message).getBytes());
ret = "写出成功";
} catch (IOException e) {
throw new Exception(e.getMessage());
}
// 关闭输出流
// 关闭输出流,让输出流成为垃圾,让系统回收
// 通知系统释放该文件相关的资源
try {
fos.close();
} catch (IOException e) {
throw new Exception(e.getMessage());
}
return ret;
}
文章均为工作中遇到特殊情况所写,不足之处请指出