1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > java xlsm_poi读取excel(xls和xlsx xlsm)给定单元格内容

java xlsm_poi读取excel(xls和xlsx xlsm)给定单元格内容

时间:2018-08-07 14:42:18

相关推荐

java xlsm_poi读取excel(xls和xlsx xlsm)给定单元格内容

使用到的jar包

xls和xlsx文件要读取的内容均在(2,2)单元格中,且均为String类型(ver3 1.1.3);

xlsm文件要读取sheet名为"システム管理"的(3,2)单元格中的内容,且为Numeric类型(version 3.1),另外"システム管理"sheet页为隐藏sheet页;

注意单元格数据类型不都是String。

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

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

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.ss.usermodel.Workbook;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class xls_xlsx_xlsm_ionew {

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

String path = "D:\\8月開発案件\\01:要件定義\\01:要件定義\\04:版数チェック\\Excel\\";

String fileName = "DB一覧";

String fileType = "xlsm";

/*

String fileName = "abc";

String fileType = "xlsx";

*/

/*

String fileName = "fb";

String fileType = "xls";

*/

read(path, fileName, fileType);

}

public static void read(String path, String fileName, String fileType)

throws IOException {

InputStream stream = new FileInputStream(path + fileName + "."

+ fileType);

Workbook wb = null;

if (fileType.equals("xls")) {

wb = new HSSFWorkbook(stream);

// 读取excel中第一个sheet页的(2,2)单元格

// (列,行),从0开始

Sheet sheet = wb.getSheetAt(0);

sheet.getSheetName();

Row row = sheet.getRow(2);

Cell cell = row.getCell(2);

//ver31.1.3

System.out.print(cell.getStringCellValue());

} else if (fileType.equals("xlsx")) {

wb = new XSSFWorkbook(stream);

// 读取excel中第一个sheet页的(2,2)单元格

// (列,行),从0开始

Sheet sheet = wb.getSheetAt(0);

sheet.getSheetName();

Row row = sheet.getRow(2);

Cell cell = row.getCell(2);

//ver31.1.3

System.out.print(cell.getStringCellValue());

} else if (fileType.equals("xlsm")) {

wb = new XSSFWorkbook(stream);

int numOfSheets = wb.getNumberOfSheets();

for (int i = 0; i < numOfSheets; i++) {

Sheet sheet = wb.getSheetAt(i);

String sname = sheet.getSheetName();

if (sname.equals("システム管理")) {

Row row = sheet.getRow(3);

//获取单元格内容的方式一

//cell类型为Numeric,故采用getNumericCellValue()方法

//Cell cell = row.getCell(2);

//version3.1

//System.out.print(cell.getNumericCellValue());

//获取单元格内容的方式二

row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);

//Cannot get a text value from a numeric cell,故先将cell类型设置为String型

System.out.print(row.getCell(2).getStringCellValue());

}

}

} else {

System.out.println("您输入的excel格式不正确");

}

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。