當前位置:首頁 » 編程語言 » 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要雙擊才顯示換行

在開始選項卡下面有個玩意叫自動換行,點一下就好了。

熱點內容
土金木配置怎麼樣 發布:2024-04-26 18:52:50 瀏覽:610
這台電腦如何訪問另一台電腦伺服器 發布:2024-04-26 18:51:08 瀏覽:627
怎麼快速了解電腦的配置 發布:2024-04-26 18:42:11 瀏覽:997
rsa加密演算法例子 發布:2024-04-26 18:40:29 瀏覽:243
thinkphp緩存關閉 發布:2024-04-26 18:19:32 瀏覽:96
linux信號捕捉 發布:2024-04-26 18:19:27 瀏覽:934
編譯有哪兩種模式 發布:2024-04-26 17:53:30 瀏覽:871
伺服器電腦上能用嗎 發布:2024-04-26 17:44:42 瀏覽:560
組件式編程 發布:2024-04-26 17:19:57 瀏覽:943
電子兒童存錢罐如何改密碼 發布:2024-04-26 17:19:13 瀏覽:601