「javaxssfrow」javaxssfrow导出换行

博主:adminadmin 2022-12-22 18:21:10 63

本篇文章给大家谈谈javaxssfrow,以及javaxssfrow导出换行对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

java把HSSF全部替换成XSSF,然后来写excel2007报错?

首先:确定jar包是否已经导入

需导入jxl.jar,poi-3.11-20141221.jar,commons-io-2.2.jar除外的jar包

其次看jdk版本是否大于1.6.0_18,若没有,则会在new XSSFWorkbook()时报错

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编程中用Apache POI 怎么用SXSSFWorkbook对已存在的excel(.xlsx)操作进行写数据操作

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

这个需要你自己写方法. 遍历你的表头行每个单元格的数据

对比你传的参数 匹配时 返回 该单元格的列号. 然后再用不同的row去get得到的列号

Java对Excel解析(求助)

这篇blog主要是讲述java中poi读取excel,而excel的版本包括:2003-2007和2010两个版本, 即excel的后缀名为:xls和xlsx。

读取excel和MySQL相关: java的poi技术读取Excel数据到MySQL

代码如下

/**

 * 

 */

package com.b510.common;

/**

 * @author Hongten

 * @created 2014-5-21

 */

public class Common {

    public static final String OFFICE_EXCEL_2003_POSTFIX = "xls";

    public static final String OFFICE_EXCEL_2010_POSTFIX = "xlsx";

    public static final String EMPTY = "";

    public static final String POINT = ".";

    public static final String LIB_PATH = "lib";

    public static final String STUDENT_INFO_XLS_PATH = LIB_PATH + "/student_info" + POINT + OFFICE_EXCEL_2003_POSTFIX;

    public static final String STUDENT_INFO_XLSX_PATH = LIB_PATH + "/student_info" + POINT + OFFICE_EXCEL_2010_POSTFIX;

    public static final String NOT_EXCEL_FILE = " : Not the Excel file!";

    public static final String PROCESSING = "Processing...";

}

/**

 * 

 */

package com.b510.excel;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.util.ArrayList;

import java.util.List;

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

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

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

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

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;

import com.b510.common.Common;

import com.b510.excel.util.Util;

import com.b510.excel.vo.Student;

/**

 * @author Hongten

 * @created 2014-5-20

 */

public class ReadExcel {

    

    /**

     * read the Excel file

     * @param path the path of the Excel file

     * @return

     * @throws IOException

     */

    public ListStudent readExcel(String path) throws IOException {

        if (path == null || Common.EMPTY.equals(path)) {

            return null;

        } else {

            String postfix = Util.getPostfix(path);

            if (!Common.EMPTY.equals(postfix)) {

                if (Common.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)) {

                    return readXls(path);

                } else if (Common.OFFICE_EXCEL_2010_POSTFIX.equals(postfix)) {

                    return readXlsx(path);

                }

            } else {

                System.out.println(path + Common.NOT_EXCEL_FILE);

            }

        }

        return null;

    }

    /**

     * Read the Excel 2010

     * @param path the path of the excel file

     * @return

     * @throws IOException

     */

    public ListStudent readXlsx(String path) throws IOException {

        System.out.println(Common.PROCESSING + path);

        InputStream is = new FileInputStream(path);

        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);

        Student student = null;

        ListStudent list = new ArrayListStudent();

        // Read the Sheet

        for (int numSheet = 0; numSheet  xssfWorkbook.getNumberOfSheets(); numSheet++) {

            XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);

            if (xssfSheet == null) {

                continue;

            }

            // Read the Row

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

                XSSFRow xssfRow = xssfSheet.getRow(rowNum);

                if (xssfRow != null) {

                    student = new Student();

                    XSSFCell no = xssfRow.getCell(0);

                    XSSFCell name = xssfRow.getCell(1);

                    XSSFCell age = xssfRow.getCell(2);

                    XSSFCell score = xssfRow.getCell(3);

                    student.setNo(getValue(no));

                    student.setName(getValue(name));

                    student.setAge(getValue(age));

                    student.setScore(Float.valueOf(getValue(score)));

                    list.add(student);

                }

            }

        }

        return list;

    }

    /**

     * Read the Excel 2003-2007

     * @param path the path of the Excel

     * @return

     * @throws IOException

     */

    public ListStudent readXls(String path) throws IOException {

        System.out.println(Common.PROCESSING + path);

        InputStream is = new FileInputStream(path);

        HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);

        Student student = null;

        ListStudent list = new ArrayListStudent();

        // Read the Sheet

        for (int numSheet = 0; numSheet  hssfWorkbook.getNumberOfSheets(); numSheet++) {

            HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);

            if (hssfSheet == null) {

                continue;

            }

            // Read the Row

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

                HSSFRow hssfRow = hssfSheet.getRow(rowNum);

                if (hssfRow != null) {

                    student = new Student();

                    HSSFCell no = hssfRow.getCell(0);

                    HSSFCell name = hssfRow.getCell(1);

                    HSSFCell age = hssfRow.getCell(2);

                    HSSFCell score = hssfRow.getCell(3);

                    student.setNo(getValue(no));

                    student.setName(getValue(name));

                    student.setAge(getValue(age));

                    student.setScore(Float.valueOf(getValue(score)));

                    list.add(student);

                }

            }

        }

        return list;

    }

    @SuppressWarnings("static-access")

    private String getValue(XSSFCell xssfRow) {

        if (xssfRow.getCellType() == xssfRow.CELL_TYPE_BOOLEAN) {

            return String.valueOf(xssfRow.getBooleanCellValue());

        } else if (xssfRow.getCellType() == xssfRow.CELL_TYPE_NUMERIC) {

            return String.valueOf(xssfRow.getNumericCellValue());

        } else {

            return String.valueOf(xssfRow.getStringCellValue());

        }

    }

    @SuppressWarnings("static-access")

    private String getValue(HSSFCell hssfCell) {

        if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {

            return String.valueOf(hssfCell.getBooleanCellValue());

        } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {

            return String.valueOf(hssfCell.getNumericCellValue());

        } else {

            return String.valueOf(hssfCell.getStringCellValue());

        }

    }

}

/**

 * 

 */

package com.b510.excel.client;

import java.io.IOException;

import java.util.List;

import com.b510.common.Common;

import com.b510.excel.ReadExcel;

import com.b510.excel.vo.Student;

/**

 * @author Hongten

 * @created 2014-5-21

 */

public class Client {

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

        String excel2003_2007 = Common.STUDENT_INFO_XLS_PATH;

        String excel2010 = Common.STUDENT_INFO_XLSX_PATH;

        // read the 2003-2007 excel

        ListStudent list = new ReadExcel().readExcel(excel2003_2007);

        if (list != null) {

            for (Student student : list) {

                System.out.println("No. : " + student.getNo() + ", name : " + student.getName() + ", age : " + student.getAge() + ", score : " + student.getScore());

            }

        }

        System.out.println("======================================");

        // read the 2010 excel

        ListStudent list1 = new ReadExcel().readExcel(excel2010);

        if (list1 != null) {

            for (Student student : list1) {

                System.out.println("No. : " + student.getNo() + ", name : " + student.getName() + ", age : " + student.getAge() + ", score : " + student.getScore());

            }

        }

    }

}

/**

 * 

 */

package com.b510.excel.util;

import com.b510.common.Common;

/**

 * @author Hongten

 * @created 2014-5-21

 */

public class Util {

    /**

     * get postfix of the path

     * @param path

     * @return

     */

    public static String getPostfix(String path) {

        if (path == null || Common.EMPTY.equals(path.trim())) {

            return Common.EMPTY;

        }

        if (path.contains(Common.POINT)) {

            return path.substring(path.lastIndexOf(Common.POINT) + 1, path.length());

        }

        return Common.EMPTY;

    }

}

/**

 * 

 */

package com.b510.excel.vo;

/**

 * Student

 * 

 * @author Hongten

 * @created 2014-5-18

 */

public class Student {

    /**

     * id   

     */

    private Integer id;

    /**

     * 学号

     */

    private String no;

    /**

     * 姓名

     */

    private String name;

    /**

     * 学院

     */

    private String age;

    /**

     * 成绩

     */

    private float score;

    public Integer getId() {

        return id;

    }

    public void setId(Integer id) {

        this.id = id;

    }

    public String getNo() {

        return no;

    }

    public void setNo(String no) {

        this.no = no;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public String getAge() {

        return age;

    }

    public void setAge(String age) {

        this.age = age;

    }

    public float getScore() {

        return score;

    }

    public void setScore(float score) {

        this.score = score;

    }

}

java生成excel设置列宽,汉字问题

貌似只能大概猜测。因为英文的字符不是等宽的,另外也和font-size, font-family有关。

如果是12号字体,一个汉字的宽度应该是12像素,一个字母应该大致是6像素。

你还需要将1像素转化为1excel单元格的宽度单位。

javaxssfrow的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于javaxssfrow导出换行、javaxssfrow的信息别忘了在本站进行查找喔。

The End

发布于:2022-12-22,除非注明,否则均为首码项目网原创文章,转载请注明出处。