java使用xssfworkbook读取excel数据,sxssfworkbook读取excel

本文目录一览:

java怎么读取excel数据

引入poi的jar包,大致如下:

读取代码如下,应该能看得明白吧

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStream;

import java.math.BigDecimal;

import java.text.DecimalFormat;

import java.text.SimpleDateFormat;

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

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

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

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

public class ExcelUtil2007 {

/**读取excel文件流的指定索引的sheet

 * @param inputStream excel文件流

 * @param sheetIndex 要读取的sheet的索引

 * @return

 * @throws FileNotFoundException

 * @throws IOException

 */

public static XSSFSheet readExcel(InputStream inputStream,int sheetIndex) throws FileNotFoundException, IOException

{

return readExcel(inputStream).getSheetAt(sheetIndex);

}

/**读取excel文件的指定索引的sheet

 * @param filePath excel文件路径

 * @param sheetIndex 要读取的sheet的索引

 * @return

 * @throws IOException 

 * @throws FileNotFoundException 

 */

public static XSSFSheet readExcel(String filePath,int sheetIndex) throws FileNotFoundException, IOException

{

return readExcel(filePath).getSheetAt(sheetIndex);

}

/**读取excel文件的指定索引的sheet

 * @param filePath excel文件路径

 * @param sheetName 要读取的sheet的名称

 * @return

 * @throws IOException 

 * @throws FileNotFoundException 

 */

public static XSSFSheet readExcel(String filePath,String sheetName) throws FileNotFoundException, IOException

{

return readExcel(filePath).getSheet(sheetName);

}

/**读取excel文件,返回XSSFWorkbook对象

 * @param filePath excel文件路径

 * @return 

 * @throws FileNotFoundException

 * @throws IOException

 */

public static XSSFWorkbook readExcel(String filePath) throws FileNotFoundException, IOException

{

XSSFWorkbook wb=new XSSFWorkbook(new FileInputStream(filePath));

return wb;

}

/**读取excel文件流,返回XSSFWorkbook对象

 * @param inputStream excel文件流

 * @return

 * @throws FileNotFoundException

 * @throws IOException

 */

public static XSSFWorkbook readExcel(InputStream inputStream) throws FileNotFoundException, IOException

{

XSSFWorkbook wb=new XSSFWorkbook(inputStream);

return wb;

}

/***读取excel中指定的单元格,并返回字符串形式的值

 * 1.数字

 * 2.字符

 * 3.公式(返回的为公式内容,非单元格的值)

 * 4.空

 * @param st 要读取的sheet对象

 * @param rowIndex 行索引

 * @param colIndex 列索引

 * @param isDate 是否要取的是日期(是则返回yyyy-MM-dd格式的字符串)

 * @return

 */

public static String getCellString(XSSFSheet st,int rowIndex,int colIndex,boolean isDate){

String s=””;

XSSFRow row=st.getRow(rowIndex);

if(row == null) return “”;

XSSFCell cell=row.getCell(colIndex);

if(cell == null) return “”;

if (cell.getCellType() == 0) {//数字

if(isDate)s=new SimpleDateFormat(“yyyy-MM-dd”).format(cell.getDateCellValue());

else s = trimPointO(String.valueOf(getStringValue(cell)).trim());

}else if (cell.getCellType() == 1){//字符(excel中的空格,不是全角,也不是半角,不知道是神马,反正就是” “这个)

s=cell.getRichStringCellValue().getString().replaceAll(” “, ” “).trim();

// s=cell.getStringCellValue();//07API新增,好像跟上一句一致

}

else if (cell.getCellType() == 2){//公式

s=cell.getCellFormula();

}

else if (cell.getCellType() == 3){//空

s=””;

}

return s;

}

/**如果数字以 .0 结尾,则去掉.0

 * @param s

 * @return

 */

public static String trimPointO(String s) {

if (s.endsWith(“.0”))

return s.substring(0, s.length() – 2);

else

return s;

}

/**处理科学计数法和百分比模式的数字单元格

 * @param cell

 * @return

 */

public static String getStringValue(XSSFCell cell) {

String sValue = null;

short dataFormat = cell.getCellStyle().getDataFormat();

double d = cell.getNumericCellValue();

BigDecimal b = new BigDecimal(Double.toString(d));

//百分比样式的

if (dataFormat == 0xa || dataFormat == 9) {

b=b.multiply(new BigDecimal(100));

//String temp=b.toPlainString();

DecimalFormat df=new DecimalFormat(“0.00”);//保留两位小数的百分比格式

sValue = df.format(b) + “%”;

}else{

sValue = b.toPlainString();

}

return sValue;

}

}

《JAVA》编程中怎么用SXSSFWorkbook对已存在的excel操作进行写数据操作

XSSFWorkbook wb=new XSSFWorkbook(参数);中的参数是InputStream ,你直接XSSFWorkbook wb=new XSSFWorkbook(fs);就可以了。

第一步查询数据–这一步读者自行实现自己的数据查询 ListPointInfo points = null;

points = this.dao.getAllCollect(userId);

final MapString, ListPointInfo pointMap = new HashMap();

for (final PointInfo pointInfo : points) {

final String pt = pointInfo.getPointType(); if (pointMap.containsKey(pt)) {final ListPointInfo subList = pointMap.get(pt);

subList.add(pointInfo);

} else {final ListPointInfo subList = new ArrayList();subList.add(pointInfo);

pointMap.put(pt, subList

第二步:生成工作簿

final SXSSFWorkbook wb = new SXSSFWorkbook();

// 对每一种类型生成一个sheet

for (final Map.EntryString, ListPointInfo entry : pointMap.entrySet()) {

final ListPointInfo pts = entry.getValue();

// 获取每种类型的名字–作为sheet显示名称–如果不需要分sheet可忽略

String typeName = “”;

if (this.dao.getTypeByTypeCode(pts.get(0).getPointType()) != null) {

typeName = this.dao.getTypeByTypeCode(pts.get(0).getPointType()).getPointTypeName();

}

final Sheet sheet = wb.createSheet(typeName);

//生成用于插入图片的容器–这个方法返回的类型在老api中不同

final Drawing patriarch = sheet.createDrawingPatriarch();

// 为sheet1生成第一行,用于放表头信息

final Row row = sheet.createRow(0);

// 第一行的第一个单元格的值

Cell cell = row.createCell((short) 0);

cell.setCellValue(“详细地址”);

cell = row.createCell((short) 1);

cell.setCellValue(“经度”);

cell = row.createCell((short) 2);

cell.setCellValue(“纬度”);

cell = row.createCell((short) 3);

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

final Row each = sheet.createRow(i + 1);

Cell infoCell = each.createCell((short) 0);

infoCell.setCellValue(pts.get(i).getAddrDetail());

infoCell = each.createCell((short) 1);

infoCell.setCellValue(pts.get(i).getX());

infoCell = each.createCell((short) 2);

infoCell.setCellValue(pts.get(i).getY());

infoCell = each.createCell((short) 3);

//查询获取图片路径信息–该步读者自定义

PointPic pic = this.dao.getPicInfoByPointId(pts.get(i).getId());

try {

if (pic != null) {

for (int k = 0; k 6; k++) {//因为有六张图片,所以循环6次

final short colNum = (short) (4+k);

infoCell = each.createCell(colNum);

BufferedImage img = null;

switch (k) {

case 0:

if (!StringUtils.isEmpty(pic.getPicOneAddr())) {

File imgFile = new File(pic.getPicOneAddr());

img = ImageIO.read(imgFile);

imgFile = null;

}

break;

case 1:

if (!StringUtils.isEmpty(pic.getPicTwoAddr())) {

File imgFile = new File(pic.getPicTwoAddr());

img = ImageIO.read(imgFile);

imgFile = null;

}

break;

case 2:

if (!StringUtils.isEmpty(pic.getPicThreeAddr())) {

File imgFile = new File(pic.getPicThreeAddr());

img = ImageIO.read(imgFile);

imgFile = null;

}

break;

case 3:

if (!StringUtils.isEmpty(pic.getPicFourAddr())) {

File imgFile = new File(pic.getPicFourAddr());

img = ImageIO.read(imgFile);

imgFile = null;

}

break;

case 4:

if (!StringUtils.isEmpty(pic.getPicFiveAddr())) {

File imgFile = new File(pic.getPicFiveAddr());

img = ImageIO.read(imgFile);

imgFile = null;

}

break;

case 5:

if (!StringUtils.isEmpty(pic.getPicSixAddr())) {

File imgFile = new File(pic.getPicSixAddr());

img = ImageIO.read(imgFile);

imgFile = null;

}

break;

}

ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();

ImageIO.write(img, “jpg”, byteArrayOut);

img = null;

//设置每张图片插入位置

final XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, colNum,

i + 1, (short) (colNum + 1), i + 2);//参数为图片插入在表格的坐标,可以自行查看api研究参数

anchor.setAnchorType(0);

// 插入图片

patriarch.createPicture(anchor, wb.addPicture(

byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));

byteArrayOut.close();

byteArrayOut = null;

}

pic = null;

}

} catch (final Exception e) {

e.printStackTrace();

}

}

}

final ByteArrayOutputStream os = new ByteArrayOutputStream();

try {

wb.write(os);

} catch (final IOException e) {

e.printStackTrace();

}

final byte[] content = os.toByteArray();

final String url = Var.BASE_URL+ File.separator + “output.xls”;//读者自定义路径

final File file = new File(url);// Excel文件生成后存储的位置。

OutputStream fos = null;

try {

fos = new FileOutputStream(file);

fos.write(content);

os.close();

fos.close();

} catch (final Exception e) {

e.printStackTrace();

}

return url;//文件保存成功

Java POI读取Excel的时候怎么按列读取

按列读取的方法:

String pathname = “E:\\files\\title.xlsx”;

File file = new File(pathname);

InputStream in = new FileInputStream(file);

//得到整个excel对象

XSSFWorkbook excel = new XSSFWorkbook(in);

//获取整个excel有多少个sheet

int sheets = excel.getNumberOfSheets();

//便利第一个sheet

MapString,String colMap = new HashMapString, String();

for(int i = 0 ; i sheets ; i++ ){

XSSFSheet sheet = excel.getSheetAt(i);

if(sheet == null){

continue;

}

int mergedRegions = sheet.getNumMergedRegions();

XSSFRow row2 = sheet.getRow(0);

MapInteger,String category = new HashMapInteger, String();

for(int j = 0 ; j mergedRegions; j++ ){

CellRangeAddress rangeAddress = sheet.getMergedRegion(j);

int firstRow = rangeAddress.getFirstColumn();

int lastRow = rangeAddress.getLastColumn();

category.put(rangeAddress.getFirstColumn(), rangeAddress.getLastColumn()+”-“+row2.getCell(firstRow).toString());

}

//便利每一行

for( int rowNum = 1 ; rowNum = sheet.getLastRowNum() ; rowNum++ ){

System.out.println();

XSSFRow row = sheet.getRow(rowNum);

if(row == null){

continue;

}

short lastCellNum = row.getLastCellNum();

String cate = “”;

Integer maxIndex = 0;

for( int col = row.getFirstCellNum() ; col lastCellNum ; col++ ){

XSSFCell cell = row.getCell(col);

if(cell == null ){

continue;

}

if(“”.equals(cell.toString())){

continue;

}

int columnIndex = cell.getColumnIndex();

String string = category.get(columnIndex);

if(string != null !string.equals(“”)){

String[] split = string.split(“-“);

cate = split[1];

maxIndex = Integer.parseInt(split[0]);

System.out.println(cate+”–“+cell.toString());

}else {

//如果当前便利的列编号小于等于合并单元格的结束,说明分类还是上面的分类名称

if(columnIndex=maxIndex){

System.out.println(cate+”–“+cell.toString());

}else {

System.out.println(“分类未知”+”–“+cell.toString());

}

}

}

}

}

}

原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/241437.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
小蓝小蓝
上一篇 2024-12-12 12:37
下一篇 2024-12-12 12:37

相关推荐

  • java client.getacsresponse 编译报错解决方法

    java client.getacsresponse 编译报错是Java编程过程中常见的错误,常见的原因是代码的语法错误、类库依赖问题和编译环境的配置问题。下面将从多个方面进行分析…

    编程 2025-04-29
  • Java JsonPath 效率优化指南

    本篇文章将深入探讨Java JsonPath的效率问题,并提供一些优化方案。 一、JsonPath 简介 JsonPath是一个可用于从JSON数据中获取信息的库。它提供了一种DS…

    编程 2025-04-29
  • Java腾讯云音视频对接

    本文旨在从多个方面详细阐述Java腾讯云音视频对接,提供完整的代码示例。 一、腾讯云音视频介绍 腾讯云音视频服务(Cloud Tencent Real-Time Communica…

    编程 2025-04-29
  • Java Bean加载过程

    Java Bean加载过程涉及到类加载器、反射机制和Java虚拟机的执行过程。在本文中,将从这三个方面详细阐述Java Bean加载的过程。 一、类加载器 类加载器是Java虚拟机…

    编程 2025-04-29
  • Python读取CSV数据画散点图

    本文将从以下方面详细阐述Python读取CSV文件并画出散点图的方法: 一、CSV文件介绍 CSV(Comma-Separated Values)即逗号分隔值,是一种存储表格数据的…

    编程 2025-04-29
  • Java Milvus SearchParam withoutFields用法介绍

    本文将详细介绍Java Milvus SearchParam withoutFields的相关知识和用法。 一、什么是Java Milvus SearchParam without…

    编程 2025-04-29
  • Python中读入csv文件数据的方法用法介绍

    csv是一种常见的数据格式,通常用于存储小型数据集。Python作为一种广泛流行的编程语言,内置了许多操作csv文件的库。本文将从多个方面详细介绍Python读入csv文件的方法。…

    编程 2025-04-29
  • Java 8中某一周的周一

    Java 8是Java语言中的一个版本,于2014年3月18日发布。本文将从多个方面对Java 8中某一周的周一进行详细的阐述。 一、数组处理 Java 8新特性之一是Stream…

    编程 2025-04-29
  • Java判断字符串是否存在多个

    本文将从以下几个方面详细阐述如何使用Java判断一个字符串中是否存在多个指定字符: 一、字符串遍历 字符串是Java编程中非常重要的一种数据类型。要判断字符串中是否存在多个指定字符…

    编程 2025-04-29
  • 如何用Python统计列表中各数据的方差和标准差

    本文将从多个方面阐述如何使用Python统计列表中各数据的方差和标准差, 并给出详细的代码示例。 一、什么是方差和标准差 方差是衡量数据变异程度的统计指标,它是每个数据值和该数据值…

    编程 2025-04-29

发表回复

登录后才能评论