当前位置:首页 » 编程语言 » poijavaexcel

poijavaexcel

发布时间: 2022-09-27 14:03:54

‘壹’ java用poi导出excel文件,打开导出的文件时报错,怎么办

两个原因:

1.你的excel模版本身有问题,可以尝试新建一个模版。

2.你的excel使用了一些POI不支持的函数。

解决办法:

另存是由excel重写了完整的文件,可以解决问题。

关闭文件例子:

FileOutputStream os = new FileOutputStream("workbook.xls");

wb.write(os);

os.close();

‘贰’ java中poi读取excel时报错:Unable to construct record instance,怎么解决呀

根据你的截图,错误的可能有两个,要分别测试对应一下:
1、excel文档有问题,从截图下方看(就是乱码部分)可能excel文档的第1个sheet是个被删除的sheet,所以名称是很长的乱码,导致无法读取。
修改方法:创建一个新的excel文档,然后将需要的内容以文本的形式复制进去,再调用。
2、poi的问题,这个有可能是poi和excel的版本不对应。
修改方法:下载poi的时候确定清楚里面的hkec访问版本对应的是不是你的excel文件的版本。

‘叁’ java poi怎么获取excel单元格的内容

packagee.sjtu.erplab.poi;

importjava.io.InputStream&ch=ww.xqy.chain"target="_blank"class="link-ke">FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.InputStream;
importjava.text.SimpleDateFormat;
importjava.util.Date;
importjava.util.HashMap;
importjava.util.Map;

importorg.apache.poi.hssf.usermodel.HSSFCell;
importorg.apache.poi.hssf.usermodel.HSSFDateUtil;
importorg.apache.poi.hssf.usermodel.HSSFRow;
importorg.apache.poi.hssf.usermodel.HSSFSheet;
importorg.apache.poi.hssf.usermodel.HSSFWorkbook;
importorg.apache.poi.poifs.filesystem.POIFSFileSystem;

/**
*操作Excel表格的功能类
*/
publicclassExcelReader{
privatePOIFSFileSystemfs;
privateHSSFWorkbookwb;
privateHSSFSheetsheet;
privateHSSFRowrow;

/**
*读取Excel表格表头的内容
*@paramInputStream
*@returnString表头内容的数组
*/
publicString[]readExcelTitle(InputStreamis){
try{
fs=newPOIFSFileSystem(is);
wb=newHSSFWorkbook(fs);
}catch(IOExceptione){
e.printStackTrace();
}
sheet=wb.getSheetAt(0);
row=sheet.getRow(0);
//标题总列数
intcolNum=row.getPhysicalNumberOfCells();
System.out.println("colNum:"+colNum);
String[]title=newString[colNum];
for(inti=0;i<colNum;i++){
//title[i]=getStringCellValue(row.getCell((short)i));
title[i]=getCellFormatValue(row.getCell((short)i));
}
returntitle;
}

/**
*读取Excel数据内容
*@paramInputStream
*@returnMap包含单元格数据内容的Map对象
*/
publicMap<Integer,String>readExcelContent(InputStreamis){
Map<Integer,String>content=newHashMap<Integer,String>();
Stringstr="";
try{
fs=newPOIFSFileSystem(is);
wb=newHSSFWorkbook(fs);
}catch(IOExceptione){
e.printStackTrace();
}
sheet=wb.getSheetAt(0);
//得到总行数
introwNum=sheet.getLastRowNum();
row=sheet.getRow(0);
intcolNum=row.getPhysicalNumberOfCells();
//正文内容应该从第二行开始,第一行为表头的标题
for(inti=1;i<=rowNum;i++){
row=sheet.getRow(i);
intj=0;
while(j<colNum){
//每个单元格的数据内容用"-"分割开,以后需要时用String类的replace()方法还原数据
//也可以将每个单元格的数据设置到一个javabean的属性中,此时需要新建一个javabean
//str+=getStringCellValue(row.getCell((short)j)).trim()+
//"-";
str+=getCellFormatValue(row.getCell((short)j)).trim()+"";
j++;
}
content.put(i,str);
str="";
}
returncontent;
}

/**
*获取单元格数据内容为字符串类型的数据
*
*@paramcellExcel单元格
*@returnString单元格数据内容
*/
(HSSFCellcell){
StringstrCell="";
switch(cell.getCellType()){
caseHSSFCell.CELL_TYPE_STRING:
strCell=cell.getStringCellValue();
break;
caseHSSFCell.CELL_TYPE_NUMERIC:
strCell=String.valueOf(cell.getNumericCellValue());
break;
caseHSSFCell.CELL_TYPE_BOOLEAN:
strCell=String.valueOf(cell.getBooleanCellValue());
break;
caseHSSFCell.CELL_TYPE_BLANK:
strCell="";
break;
default:
strCell="";
break;
}
if(strCell.equals("")||strCell==null){
return"";
}
if(cell==null){
return"";
}
returnstrCell;
}

/**
*获取单元格数据内容为日期类型的数据
*
*@paramcell
*Excel单元格
*@returnString单元格数据内容
*/
privateStringgetDateCellValue(HSSFCellcell){
Stringresult="";
try{
intcellType=cell.getCellType();
if(cellType==HSSFCell.CELL_TYPE_NUMERIC){
Datedate=cell.getDateCellValue();
result=(date.getYear()+1900)+"-"+(date.getMonth()+1)
+"-"+date.getDate();
}elseif(cellType==HSSFCell.CELL_TYPE_STRING){
Stringdate=getStringCellValue(cell);
result=date.replaceAll("[年月]","-").replace("日","").trim();
}elseif(cellType==HSSFCell.CELL_TYPE_BLANK){
result="";
}
}catch(Exceptione){
System.out.println("日期格式不正确!");
e.printStackTrace();
}
returnresult;
}

/**
*根据HSSFCell类型设置数据
*@paramcell
*@return
*/
(HSSFCellcell){
Stringcellvalue="";
if(cell!=null){
//判断当前Cell的Type
switch(cell.getCellType()){
//如果当前Cell的Type为NUMERIC
caseHSSFCell.CELL_TYPE_NUMERIC:
caseHSSFCell.CELL_TYPE_FORMULA:{
//判断当前的cell是否为Date
if(HSSFDateUtil.isCellDateFormatted(cell)){
//如果是Date类型则,转化为Data格式

//方法1:这样子的data格式是带时分秒的:2011-10-120:00:00
//cellvalue=cell.getDateCellValue().toLocaleString();

//方法2:这样子的data格式是不带带时分秒的:2011-10-12
Datedate=cell.getDateCellValue();
SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-dd");
cellvalue=sdf.format(date);

}
//如果是纯数字
else{
//取得当前Cell的数值
cellvalue=String.valueOf(cell.getNumericCellValue());
}
break;
}
//如果当前Cell的Type为STRIN
caseHSSFCell.CELL_TYPE_STRING:
//取得当前的Cell字符串
cellvalue=cell.getRichStringCellValue().getString();
break;
//默认的Cell值
default:
cellvalue="";
}
}else{
cellvalue="";
}
returncellvalue;

}

publicstaticvoidmain(String[]args){
try{
//对读取Excel表格标题测试
InputStreamis=newFileInputStream("d:\test2.xls");
ExcelReaderexcelReader=newExcelReader();
String[]title=excelReader.readExcelTitle(is);
System.out.println("获得Excel表格的标题:");
for(Strings:title){
System.out.print(s+"");
}

//对读取Excel表格内容测试
InputStreamis2=newFileInputStream("d:\test2.xls");
Map<Integer,String>map=excelReader.readExcelContent(is2);
System.out.println("获得Excel表格的内容:");
for(inti=1;i<=map.size();i++){
System.out.println(map.get(i));
}

}catch(FileNotFoundExceptione){
System.out.println("未找到指定路径的文件!");
e.printStackTrace();
}
}
}

‘肆’ 如何用java poi操作excel

注解类(将实体类加上该注解)
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelField
{
//导出字段在excel中的名字
String title();
}

操作类(调用方法进行导出)
@Slf4j
public class ExcelUtil {

private static final int EXCEL_NUM_LIMIT = 200000;

/**
* 通用导出方法
*/
public static <T> void writeExcel(HttpServletResponse response, String fileName, List<T> list, Class<T> cls) {
// 1.创建一个workbook,对应一个Excel文件
SXSSFWorkbook workBook = new SXSSFWorkbook();
int page = list.size() % EXCEL_NUM_LIMIT == 0 ? list.size() / EXCEL_NUM_LIMIT : list.size() / EXCEL_NUM_LIMIT + 1;
log.info("sheet数量为:{}", page);
for (int m = 0; m < page; m++) {

Field[] fields = cls.getDeclaredFields();

ArrayList<String> headList = new ArrayList<>();

for (Field f : fields) {
ExcelField field = f.getAnnotation(ExcelField.class);
if (field != null) {
headList.add(field.title());
}
}

CellStyle style = getCellStyle(workBook);
Sheet sheet = workBook.createSheet();
workBook.setSheetName(m, "sheet" + String.valueOf(m + 1));
Header header = sheet.getHeader();
header.setCenter("sheet");

// 设置Excel表的第一行即表头
Row row = sheet.createRow(0);
for (int i = 0; i < headList.size(); i++) {
Cell headCell = row.createCell(i);
headCell.setCellType(CellType.STRING);
headCell.setCellStyle(style);//设置表头样式
headCell.setCellValue(String.valueOf(headList.get(i)));
sheet.setColumnWidth(i, 15 * 256);
}

int rowIndex = 1;
log.info("开始创建sheet{}", m);
int start = (EXCEL_NUM_LIMIT * m);
int end = list.size() - start >= EXCEL_NUM_LIMIT ? start + EXCEL_NUM_LIMIT : list.size();
log.info("开始{},结束{}", start, end);
for (int i = start; i < end; i++) {
Row rowData = sheet.createRow(rowIndex);//创建数据行
T q = list.get(i);
Field[] ff = q.getClass().getDeclaredFields();
int j = 0;
for (Field f : ff) {
ExcelField field = f.getAnnotation(ExcelField.class);
if (field == null) {
continue;
}
f.setAccessible(true);
Object obj = null;
try {
obj = f.get(q);
} catch (IllegalAccessException e) {
log.error("", e);
}
Cell cell = rowData.createCell(j);
cell.setCellType(CellType.STRING);
// 当数字时
if (obj instanceof Integer) cell.setCellValue((Integer) obj);
// 当Long时
if (obj instanceof Long) cell.setCellValue((Long) obj);
// 当为字符串时
if (obj instanceof String) cell.setCellValue((String) obj);
// 当为布尔时
if (obj instanceof Boolean) cell.setCellValue((Boolean) obj);
// 当为时间时
if (obj instanceof Date) cell.setCellValue(getFormatDate((Date) obj));
// 当为时间时
if (obj instanceof Calendar) cell.setCellValue((Calendar) obj);
// 当为小数时
if (obj instanceof Double) cell.setCellValue((Double) obj);
// 当为BigDecimal
if (obj instanceof BigDecimal) cell.setCellValue(Double.parseDouble(obj.toString()));
// 当ZonedDateTime
if (obj instanceof ZonedDateTime)
cell.setCellValue(((ZonedDateTime) obj).format(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss")));
j++;
}
rowIndex++;
}
}

responseStream(workBook, response, fileName);
}

private static void responseStream(SXSSFWorkbook workBook, HttpServletResponse response, String fileName) {
OutputStream outputStream = null;
try {
response.setContentType("application/vnd.ms-excel; charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xlsx").getBytes("UTF-8"), "ISO-8859-1"));
response.setCharacterEncoding("utf-8");
//根据传进来的file对象创建可写入的Excel工作薄
outputStream = response.getOutputStream();
log.info("数据导出Excel成功!");
workBook.write(outputStream);
} catch (IOException e) {
log.error("", e);
} finally {
try {
outputStream.close();
} catch (IOException e) {
log.error("", e);
}
}
}

/**
* 设置表头样式
*
* @param wb
* @return
*/
public static CellStyle getCellStyle(SXSSFWorkbook wb) {
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
font.setFontName("宋体");
font.setFontHeightInPoints((short) 12);//设置字体大小
font.setBold(true);//加粗
style.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());// 设置背景色
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setAlignment(HorizontalAlignment.CENTER);//让单元格居中
style.setAlignment(HorizontalAlignment.CENTER_SELECTION);// 左右居中
style.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
style.setWrapText(true);//设置自动换行
style.setFont(font);
return style;
}

public static String getFormatDate(Date date) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String dateString = formatter.format(date);
return dateString;
}

}

‘伍’ java poi导出excel

用spire.xls.jar也可以导出excel,代码更简单

  1. import com.spire.xls.ExcelVersion;

  2. import com.spire.xls.Workbook;

  3. import com.spire.xls.Worksheet;


  4. public class InsertArray {


  5. public static void main(String[] args) {


  6. //创建Workbook对象

  7. Workbook wb = new Workbook();

  8. //获取第一张工作表

  9. Worksheet sheet = wb.getWorksheets().get(0);

  10. //定义一维数据

  11. String[] oneDimensionalArray = new String[]{"苹果", "梨子", "葡萄", "香蕉"};

  12. //将数组从指定单个格开始写入工作表,true表示纵向写入,设置为false为横向写入

  13. sheet.insertArray(oneDimensionalArray, 1, 1, true);

  14. //定义二维数组

  15. String[][] twoDimensionalArray = new String[][]{

  16. {"姓名", "年龄", "性别", "学历"},

  17. {"小张", "25", "男", "本科"},

  18. {"小王", "24", "男", "本科"},

  19. {"小李", "26", "女", "本科"}

  20. };

  21. //从指定单元格开始写入二维数组到工作表

  22. sheet.insertArray(twoDimensionalArray, 1, 3);

  23. //保存文档

  24. wb.saveToFile("InsertArrays.xlsx", ExcelVersion.Version2016);

  25. }

  26. }

‘陆’ java操作poi怎么更改excel中的数据

修改完需要写入,也就是保存一下的。
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

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;

public class ChangeCell {

@SuppressWarnings("deprecation")
public static void main(String[] args) {
String fileToBeRead = "C:\\exp.xls"; // excel位置
int coloum = 1; // 比如你要获取第1列
try {
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(
fileToBeRead));
HSSFSheet sheet = workbook.getSheet("Sheet1");

for (int i = 0; i <= sheet.getLastRowNum(); i++) {
HSSFRow row = sheet.getRow((short) i);
if (null == row) {
continue;
} else {
HSSFCell cell = row.getCell((short) coloum);
if (null == cell) {
continue;
} else {
System.out.println(cell.getNumericCellValue());
int temp = (int) cell.getNumericCellValue();
cell.setCellValue(temp + 1);
}
}
}
FileOutputStream out = null;
try {
out = new FileOutputStream(fileToBeRead);
workbook.write(out);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

}

‘柒’ java excel poi 怎么导入

1、下载poi相关jar,maven的集成如下:(把${poi.version}替换成你要的版本)

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>${poi.version}</version>
<scope>provided</scope>
</dependency>

2、根据poi相关api读取sheet、row、cell,获得excel的数据:

封装row的对象,即每一行数据为一个对象,每个cell为对象里的一个属性,

整个sheet的数据装进集合里;

3、处理数据,可以对数据进行验证或其他操作;

4、写数据库操作。

‘捌’ java poi怎么获取Excel sheet页的数量

java poi获取Excel sheet页的数量方法如下:

在导出excel时候需要导出多个sheet页,后面sheet页会覆盖前面sheet页的内容。
这么写代码:
HSSFWorkbook workbook = null;
workbook=new HSSFWorkbook();

for(){

//没有现成的文件需要重新计算
HSSFSheet sheet_sin =workbook.createSheet(month_query1);
sheet_sin= makeJDL(year_query,month_query1,sheet_sin,workbook);

}

‘玖’ java poi导出excel要双击才显示换行

在开始选项卡下面有个玩意叫自动换行,点一下就好了。

热点内容
base64javaphp 发布:2024-05-07 10:30:07 浏览:848
抖音青少年模式的密码是哪里的 发布:2024-05-07 10:05:27 浏览:751
tmp文件怎么解压 发布:2024-05-07 09:59:49 浏览:938
安卓手机如何提升录歌音质 发布:2024-05-07 09:49:55 浏览:330
指法运算法 发布:2024-05-07 09:24:26 浏览:195
兜享花为什么服务器错误 发布:2024-05-07 09:12:55 浏览:126
西门子编程仿真软件 发布:2024-05-07 09:12:04 浏览:128
脚本举例 发布:2024-05-07 09:04:41 浏览:819
php经历 发布:2024-05-07 08:59:25 浏览:420
knd系统编程 发布:2024-05-07 08:55:38 浏览:219