導航:首頁 > 文件類型 > poi文件導入excel

poi文件導入excel

發布時間:2023-06-03 11:05:53

java poi怎麼導入excel數據

package poi;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFCell;
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 ReadExcel001 {
public static void main(String[] args) {
readXml("D:/test.xlsx");
System.out.println("-------------");
readXml("d:/test2.xls");
}
public static void readXml(String fileName){
boolean isE2007 = false; //判斷是否是excel2007格式
if(fileName.endsWith("xlsx"))
isE2007 = true;
try {
InputStream input = new FileInputStream(fileName); //建立輸入流
Workbook wb = null;
//根據文件格式(2003或者2007)來初始化
if(isE2007)
wb = new XSSFWorkbook(input);
else
wb = new HSSFWorkbook(input);
Sheet sheet = wb.getSheetAt(0); //獲得第一個表單
Iterator<Row> rows = sheet.rowIterator(); //獲得第一個表單的迭代器
while (rows.hasNext()) {
Row row = rows.next(); //獲得行數據
System.out.println("Row #" + row.getRowNum()); //獲得行號從0開始
Iterator<Cell> cells = row.cellIterator(); //獲得第一行的迭代器
while (cells.hasNext()) {
Cell cell = cells.next();
System.out.println("Cell #" + cell.getColumnIndex());
switch (cell.getCellType()) { //根據cell中的類型來輸出數據
case HSSFCell.CELL_TYPE_NUMERIC:
System.out.println(cell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_STRING:
System.out.println(cell.getStringCellValue());
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
System.out.println(cell.getBooleanCellValue());
break;
case HSSFCell.CELL_TYPE_FORMULA:
System.out.println(cell.getCellFormula());
break;
default:
System.out.println("unsuported sell type");
break;
}
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

參考自http://blog.csdn.net/shuwei003/article/details/6741649

Ⅱ 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模板中。最好有實例參考,謝謝。

這是我之前寫的用反射的將數據導入到excel中的類,具體實現,代碼里有注釋。不知道樓主持久層用的什麼東東?如果是its,建議使用ibatis的rowhandler,導出部分的實現,和下面這個類也很類似,樓主自己改改吧,這樣性能會高一些,尤其是在你處理的要寫入文件的數據,比較多的情況下。
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;

import cn.emag.framework.Util.LogName;

/**
* 導出成excel文件工具
*/
public class Export2ExcelUtil
{

private static Logger log = Logger.getLogger(LogName.ERROR_LOG);

private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
/**
* 生成excel文件存入伺服器
* @param importdata 待導入excle文件的內容
* @param header excel」表頭「部分內容
* @param attr 與」表頭「順序對應的importdata中的成員變數名,首字母大寫
* @param fileName 導入到目標文件中,完整路徑
*/
public static void export2exc(List<Object> importdata,String[] header,String[] attr, String fileName)
{
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
// 創建頭文件
writeHeader(header,sheet,wb);
// 創建文件內容
int i=1;
HSSFRow row;
for(Object object:importdata)
{
row = sheet.createRow(i++);
writeBody(object, attr, row);
}
// 寫入文件
OutputStream os = null;
try
{
os = new FileOutputStream(fileName);
wb.write(os);
}
catch (Exception e)
{
log.error("寫入文件失敗",e);
}
finally
{
try
{
os.close();
}
catch (IOException e)
{
log.error("寫入文件失敗",e);
}
}
}

/**
* 創建文件頭
* @param header 頭內容
* @param sheet
*/
public static void writeHeader(String[] header,HSSFSheet sheet,HSSFWorkbook wb)
{

HSSFRow row = sheet.createRow(0);
HSSFCellStyle cellstype = wb.createCellStyle();
cellstype = wb.createCellStyle();
cellstype.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
cellstype.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cellstype.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellstype.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cellstype.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellstype.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellstype.setAlignment(HSSFCellStyle.ALIGN_CENTER);
HSSFCell cell;
HSSFRichTextString str;
int n = 0;
for (String head : header)
{
sheet.setColumnWidth(n, 4000);
cell = row.createCell(n++);
cell.setCellStyle(cellstype);
str = new HSSFRichTextString(head);
cell.setCellValue(str);
}
}

/**
* 寫行內容
* @param object
* @param atrr
* @param row
* @throws Exception
*/
public static void writeBody(Object object,String[] attr,HSSFRow row)
{
int n = 0;
HSSFCell cell;
Method method;
HSSFRichTextString str;
String content=null;
for(String atr : attr)
{
cell = row.createCell(n++);
try
{
method = object.getClass().getMethod("get"+atr);
Object o = method.invoke(object);
if(null!=o)
{
if(o instanceof Date)
{
content=format.format(o);
}else
{
content = String.valueOf( method.invoke(object));
}

}else
{
content=null;
}
}
catch (SecurityException e)
{
log.error("excel寫入單元格內容失敗",e);
}
catch (IllegalArgumentException e)
{
log.error("excel寫入單元格內容失敗",e);
}
catch (NoSuchMethodException e)
{
log.error("excel寫入單元格內容失敗",e);
}
catch (IllegalAccessException e)
{
log.error("excel寫入單元格內容失敗",e);
}
catch (InvocationTargetException e)
{
log.error("excel寫入單元格內容失敗",e);
}
str = new HSSFRichTextString(content);
cell.setCellValue(str);
}

}

}

Ⅳ poi導入excel

方法/步驟

Ⅳ poi如何去寫入excel文件

直接全部在action裡面寫的,這個就不多說了,直接上代碼:

public String executeExcel() throws Exception{ String realPath = ServletActionContext.getServletContext().getRealPath("/fileupload");
System.out.println(fileFileName);
String filePath = "";
if(this.file!=null){
File saveFile = new File(new File(realPath),this.fileFileName);
filePath = realPath+"\\"+this.fileFileName;
System.out.println(filePath);
if(!saveFile.getParentFile().exists()){
saveFile.getParentFile().mkdirs(); }
FileUtils.File(file, saveFile); }
this.exlToDB(filePath);
ActionContext.getContext().put("message","導入成功");
return "success"; } //讀取excel2007,並把數據插入資料庫
public void exlToDB(String filePath){ boolean flag = true;
AllKpi akpi = new AllKpi(); try { // 文件流指向excel文件
FileInputStream fin=new FileInputStream(filePath);
XSSFWorkbook workbook = new XSSFWorkbook(fin);// 創建工作薄
XSSFSheet sheet = workbook.getSheetAt(0);// 得到工作表
XSSFRow row = null;// 對應excel的行
XSSFCell cell = null;// 對應excel的列
int totalRow = sheet.getLastRowNum();// 得到excel的總記錄條數
System.out.println(totalRow); // 以下的欄位一一對應資料庫表的欄位
float idd = 0.0f;
String id = "";
String Name = "";
String DEPT_NAME = "";
String Weight = "";
<span></span>String ALGORITHM = "";
String text = " ";
//String sql = "insert into DSP_TJ_KPI values(DSP_TJ_KPI_SEQ.nextval,?,?,?,'無',?)";
for (int i = 1; i <= totalRow; i++) {
row = sheet.getRow(i);
//System.out.println(row.getCell(0).toString());
if(row.getCell(0) != null && !"".equals(row.getCell(0)) && row.getCell(1) != null && !"".equals(row.getCell(1)) && row.getCell(2) != null && !"".equals(row.getCell(2)) && row.getCell(3) != null && !"".equals(row.getCell(3))){
cell = row.getCell((short) 0);
Name = cell.toString();
System.out.println(Name);
cell = row.getCell((short) 1);
Weight = cell.toString();
System.out.println(Weight);
cell = row.getCell((short) 2);
DEPT_NAME = cell.toString();
System.out.println(DEPT_NAME);
cell = row.getCell((short) 3);
ALGORITHM = cell.toString();
System.out.println(ALGORITHM);
akpi.setAllkpiName(Name);
akpi.setAllkpiDeptName(DEPT_NAME);
akpi.setAllkpiWeight(Weight);
akpi.setAlgorithm(ALGORITHM);
akpi.setText(text);
allKpiService.addAllKpi(akpi); //以下注釋代碼為連接jdbc測試代碼塊
/*pst = con.prepareStatement(sql);
//pst.setString(1, student_id);
pst.setString
(1, DEPT_NAME);
pst.setString
(2, Name);
pst.setString
(3, Weight);
<span></span>pst.setString(4, ALGORITHM);
pst.execute();*/
System.out.println("preparestatement successful"); } }
/*pst.close();
con.close();*/
fin.close(); } catch (FileNotFoundException e)
{
flag = false;
e.printStackTrace();
}
catch (IOException ex)
{
flag = false;
ex.printStackTrace();
}

Ⅵ poi導入excel時,excel不是標準的excel文件,導致報錯,需要另存為下才可以導入,求解決辦法

你可考慮過把JXL和POI配合起來使用?即:用JXL從非標準的EXCEL里讀取數據然後用POI來另存為EXCEL,然後再用POI來使用它

Ⅶ 如何使用POI對Excel表進行導入和導出

導入POI的jar包
新建一個項目,在根目錄在新建一個lib文件夾,將jar包復制粘貼到lib文件夾後,右鍵將其添加到項目的build path中,最後的結果如圖所示:

2
編寫java類,新建一個實體類,比如我們要導出資料庫的有關電腦的信息,那麼就建一個Computer實體類,代碼如下:
package com.qiang.poi;
public class Computer {
private int id;
private String name;
private String description;
private double price;
private double credit;
public int getId() {
return id;
}
public Computer(int id, String name, String description, double price,
double credit) {
super();
this.id = id;
this.name = name;
this.description = description;
this.price = price;
this.credit = credit;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public double getCredit() {
return credit;
}
public void setCredit(double credit) {
this.credit = credit;
}
}
3
新建一個寫入excel的方法,如write2excel,參數可以後面邊寫邊決定(站在一個不熟悉POI的角度)
public static void write2Excel(){}
4
創建操作Excel的HSSFWorkbook對象
HSSFWorkbook excel= new HSSFWorkbook();
創建HSSFSheet對象
Excel中的一個sheet(工作表)對應著java中的一個HSSFSheet對象,利用HSSFWorkbook對象可以創建一個HSSFSheet對象
如:創建一個sheet名為computer的excel
HSSFSheet sheet = excel.createSheet("computer");
創建第一行標題信息的HSSFRow對象
我們都知道excel是表格,即由一行一行組成的,那麼這一行在java類中就是一個HSSFRow對象,我們通過HSSFSheet對象就可以創建HSSFRow對象
如:創建表格中的第一行(我們常用來做標題的行) HSSFRow firstRow = sheet.createRow(0); 注意下標從0開始
創建標題行中的HSSFCell數組
當然,excel中每一行是由若干個單元格,我們常稱為cell,它對應著java中的HSSFCell對象
如:創建5個單元格 HSSFCell cells[] = new HSSFCell[5];
//假設我們一行有五列數據
創建標題數據,並通過HSSFCell對象的setCellValue()方法對每個單元格進行賦值
既然單元格都准備好了,那最後是不是該填充數據了呀。對的,沒錯。填充數據之前,得把數據准備好吧,
數據:String[] titles = new String[]{"id","name","description","price","credit"};
插入一句話: 在這個時代,能讓機器做的,盡量不讓人來做,記住這句話。
好的,繼續。現在就通過for循環來填充第一行標題的數據
for (int i = 0; i < 5; i++) {
cells[0] = firstRow.createCell(i);
cells[0].setCellValue(titles[i]);
}
數據分析
第一行標題欄創建完畢後,就准備填充我們要寫入的數據吧,在java中,面向對象給我們帶來的好處在這里正好體現了,沒錯
把要填寫的數據封裝在對象中,即一行就是一個對象,n行就是一個對象列表嘛,好的,走起。
創建對象Computer,私有屬性id,name,description,price,credit,以及各屬性的setter和getter方法,如步驟二所示。
假設我們要寫入excel中的數據從資料庫查詢出來的,最後就生成了一個List<Computer>對象computers
數據寫入
具體數據有了,又該讓機器幫我們幹活了,向excel中寫入數據。
for (int i = 0; i < computers.size(); i++) {
HSSFRow row = sheet.createRow(i + 1);
Computer computer = computers.get(i);
HSSFCell cell = row.createCell(0);
cell.setCellValue(computer.getId());
cell = row.createCell(1);
cell.setCellValue(computer.getName());
cell = row.createCell(2);
cell.setCellValue(computer.getDescription());
cell = row.createCell(3);
cell.setCellValue(computer.getPrice());
cell = row.createCell(4);
cell.setCellValue(computer.getCredit());
}
將數據真正的寫入excel文件中
做到這里,數據都寫好了,最後就是把HSSFWorkbook對象excel寫入文件中了。
OutputStream out = null;
try {
out = new FileOutputStream(file);
excel.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("數據已經寫入excel"); //溫馨提示
看看我的main方法吧
public static void main(String[] args) throws IOException {
File file = new File("test1.xls");
if(!file.exists()){
file.createNewFile();
}
List<Computer> computers = new ArrayList<Computer>();
computers.add(new Computer(1,"宏碁","筆記本電腦",3333,9.0));
computers.add(new Computer(2,"蘋果","筆記本電腦,一體機",8888,9.6));
computers.add(new Computer(3,"聯想","筆記本電腦,台式機",4444,9.3));
computers.add(new Computer(4, "華碩", "筆記本電腦,平板電腦",3555,8.6));
computers.add(new Computer(5, "註解", "以上價格均為捏造,如有雷同,純屬巧合", 1.0, 9.9));
write2excel(computers, file);
}
工程目錄及執行main方法後的test1.xls數據展示

源碼分享,computer就不貼了
package com.qiang.poi;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
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;
public class ReadExcel {
public static void main(String[] args) throws IOException {
File file = new File("test1.xls");
if(!file.exists()){
file.createNewFile();
}
List<Computer> computers = new ArrayList<Computer>();
computers.add(new Computer(1,"宏碁","筆記本電腦",3333,9.0));
computers.add(new Computer(2,"蘋果","筆記本電腦,一體機",8888,9.6));
computers.add(new Computer(3,"聯想","筆記本電腦,台式機",4444,9.3));
computers.add(new Computer(4, "華碩", "筆記本電腦,平板電腦",3555,8.6));
computers.add(new Computer(5, "註解", "以上價格均為捏造,如有雷同,純屬巧合", 1.0, 9.9));
write2excel(computers, file);
}

public static void write2excel(List<Computer> computers,File file) {
HSSFWorkbook excel = new HSSFWorkbook();
HSSFSheet sheet = excel.createSheet("computer");
HSSFRow firstRow = sheet.createRow(0);
HSSFCell cells[] = new HSSFCell[5];
String[] titles = new String[] { "id", "name", "description", "price",
"credit" };
for (int i = 0; i < 5; i++) {
cells[0] = firstRow.createCell(i);
cells[0].setCellValue(titles[i]);
}
for (int i = 0; i < computers.size(); i++) {
HSSFRow row = sheet.createRow(i + 1);
Computer computer = computers.get(i);
HSSFCell cell = row.createCell(0);
cell.setCellValue(computer.getId());
cell = row.createCell(1);
cell.setCellValue(computer.getName());
cell = row.createCell(2);
cell.setCellValue(computer.getDescription());
cell = row.createCell(3);
cell.setCellValue(computer.getPrice());
cell = row.createCell(4);
cell.setCellValue(computer.getCredit());
}
OutputStream out = null;
try {
out = new FileOutputStream(file);
excel.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

閱讀全文

與poi文件導入excel相關的資料

熱點內容
如何設置胎壓監測數據 瀏覽:530
降噪工具 瀏覽:692
obs編程是什麼意思 瀏覽:859
怎麼看c4d打開了多少個文件 瀏覽:792
蘋果銀河高清壁紙 瀏覽:811
怎麼從蘋果電腦垃圾桶找迴文件 瀏覽:771
介面文件不能用action寫嗎 瀏覽:85
svn代碼提交規范 瀏覽:642
在宣讀多少號文件時怎麼讀數字 瀏覽:921
網站中的區域網訪問量是什麼意思 瀏覽:397
蘋果啟動助理識別不到鏡像文件 瀏覽:670
為什麼每次文件都問是否改變應用 瀏覽:232
pinterestapp怎麼進去 瀏覽:968
json實現通用的下拉框 瀏覽:524
hc在編程中是什麼意思 瀏覽:482
javamd文件怎麼打開方式 瀏覽:90
python載入mat文件格式 瀏覽:615
sw編程是什麼 瀏覽:881
網路眾籌有哪些特點 瀏覽:896
有哪些不需要會員的看動漫的app 瀏覽:533

友情鏈接