POI提供了HSSF、XSSF以及SXSSF三种方式操作Excel。
HSSF:Excel97-2003版本,扩展名为.xls。一个sheet最大行数65536,最大列数256。
XSSF:Excel2007版本开始,扩展名为.xlsx。一个sheet最大行数1048576,最大列数16384。
SXSSF:是在XSSF基础上,POI3.8版本开始提供的支持低内存占用的操作方式,扩展名为.xlsx。
1. 导入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
2. 利用HSSFWorkbook写Excel
1. 创建HSSFWorkbook对象
2. 创建对应的工作表sheet (相当于Excel左下角的每一个工作表)
3. 根据sheet来创建HSSFRow对象,拿到操作每一行的对象
4. 通过每一行的对象来创建该行中每一个单元格HSSFCell对象,来往单元格中写入数据
5. 最后定义要写入文件的输出流,利用workbook.write(stream)将数据写入文件中
public class POIWriteExcel {
public static void main(String[] args) throws IOException {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
HSSFRow row = sheet.createRow(0);
for (int i = 0; i < 4; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue("标题"+i);
}
for (int i = 1; i < 100; i++) {
HSSFRow sheetRow = sheet.createRow(i);
for (int j = 0; j < 10; j++) {
HSSFCell cell = sheetRow.createCell(j);
cell.setCellValue(i);
}
}
File file = new File(System.getProperty("user.dir") + "/src/main/resources/test.xls");
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
workbook.write(fos);
fos.close();
}
}
3. 利用HSSFWorkbook读Excel
1. 创建xls文件的读入数据流FileInputStream
2. 利用该文件数据流创建HSSFWorkbook对象
3. 同样的根据该对象获取到某一工作表Sheet的对象(因为一个Excel中可能有多个工作表)
4. 根据sheet来获得HSSFRow对象,拿到操作每一行的对象
5. 通过每一行的对象来获得该行中每一个单元格HSSFCell对象,来读取单元格中的数据
6. 最后定义要写入文件的输出流,利用workbook.write(stream)将数据写入文件中
public class ProvinceMain {
public static void main(String[] args) throws IOException {
File file = new File(System.getProperty("user.dir") + "/src/main/resources/province.xls");
FileInputStream fis = new FileInputStream(file);
POIFSFileSystem poifsFileSystem = new POIFSFileSystem(fis);
HSSFWorkbook sheets = new HSSFWorkbook(poifsFileSystem);
HSSFSheet sheet = sheets.getSheetAt(0);
int firstRowNum = sheet.getFirstRowNum();
int lastRowNum = sheet.getLastRowNum();
ArrayList<Province> provinces = new ArrayList<>();
DecimalFormat decimalFormat = new DecimalFormat("0");
for (int i = firstRowNum + 1; i <= lastRowNum; i++) {
Province province = new Province();
HSSFRow row = sheet.getRow(i);
province.setStateId(row.getCell(0).toString().substring(0, 5));
province.setStateName(row.getCell(1).toString());
province.setCityId(decimalFormat.format(row.getCell(2).getNumericCellValue()));
province.setCityName(row.getCell(3).toString());
provinces.add(province);
}
System.out.println(JSON.toJSONString(provinces));
}
}
问题解决:Java操作Excel表读取的数字变成科学计数法
当使用POI处理excel的时候,遇到了比较长的数字,虽然excel里面设置该单元格是文本类型的,但是POI的cell的类型就会变成数字类型。
而且无论数字是否小数,使用cell.getNumbericCellValue() 去获取值的时候,会得到一个double,并且当长度大一点的时候会变成科学计数法形式。
那么获取这个单元格的原始的数据,就其实是一个double怎么转换成整数的问题了。
使用DecimalFormat对这个double进行了格式化,然后使用format方法获得的String就是你想要的值了。
// 取得当前Cell的数值
// cellvalue = String.valueOf(cell.getNumericCellValue());
DecimalFormat format = new DecimalFormat("0");
cellvalue=format.format (cell.getNumericCellValue());
案例补充:
6月25日老板又叫我将txt文档转换成excel了,然后我研究了一下,工具方法代码如下
/**
* 字符串转化为输入流
* @param str
* @return
*/
public static InputStream getInputStreamFromStr(String str){
try {
ByteArrayInputStream is = new ByteArrayInputStream(str.getBytes());
return is;
} catch (Exception e) {
}
return null;
}//.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRS
/**
* 输入流转化为字符串
* @return
*/
public static String getStrFromInputStream(InputStream is){
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuffer sb = new StringBuffer();
String tmp = "";
try {
while((tmp = br.readLine())!=null){
sb.append(tmp);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 多次读取输入流,先转成ByteArrayOutputStream
*/
public static void moreReadInputStram(InputStream input){
//将InputStream对象转换成ByteArrayOutputStream
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
try {
while ((len = input.read(buffer)) > -1 ) {
byteArrayOutputStream.write(buffer, 0, len);
}
byteArrayOutputStream.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//将byteArrayOutputStream可转换成多个InputStream对象,达到多次读取InputStream效果
InputStream inputStreamA = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
InputStream inputStreamB = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
//将InputStream转换成字符串
BufferedReader br;
try {
br = new BufferedReader(new InputStreamReader(inputStreamB,"UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public class Readtxt {
/**
* 输入流转化为字符串
*
* @return
*/
public static String getStrFromInputStream(InputStream is) {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuffer sb = new StringBuffer();
String tmp = "";
try {
while ((tmp = br.readLine()) != null) {
sb.append(tmp);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws IOException {
File file = new File(System.getProperty("user.dir") + "/src/main/resources/车站信息汇总.txt");
FileInputStream fileInputStream = new FileInputStream(file);
String strFromInputStream = getStrFromInputStream(fileInputStream);
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
HSSFRow tempRow = sheet.createRow(0);
tempRow.createCell(0).setCellValue("序号");
tempRow.createCell(1).setCellValue("站名");
tempRow.createCell(2).setCellValue("三字码");
tempRow.createCell(3).setCellValue("英文名");
tempRow.createCell(4).setCellValue("拼音简写");
String[] split = strFromInputStream.split("\\|");
for (int i = 0, row = 1; i < split.length-1;i++, row++) {
// 五个一组
HSSFRow tempRows = sheet.createRow(row);
HSSFCell cell0 = tempRows.createCell(0);
cell0.setCellValue(split[i++]);
HSSFCell cell1 = tempRows.createCell(1);
cell1.setCellValue(split[i++]);
HSSFCell cell2 = tempRows.createCell(2);
cell2.setCellValue(split[i++]);
HSSFCell cell3 = tempRows.createCell(3);
cell3.setCellValue(split[i++]);
HSSFCell cell4 = tempRows.createCell(4);
cell4.setCellValue(split[i]);
}
File outPutFile = new File(System.getProperty("user.dir") + "/src/main/resources/车站.xls");
file.createNewFile();
FileOutputStream fos = new FileOutputStream(outPutFile);
workbook.write(fos);
fos.close();
}
}