當前位置:首頁 » 操作系統 » poiexcel導入資料庫

poiexcel導入資料庫

發布時間: 2023-05-15 05:44:41

① 如何使用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();
}
}
}

② java利用poi技術導入批量excel數據,並且分段存入資料庫怎麼解決

注意引入的都是poi的包,使用Cell,excel2003的.xls對應是HSSFCell,而之後的xlsx對應的則是XSSFCell,但是他們都繼承於Cell,所以使用Cell就可以使用兩種格式的excel導入了,下面解決excel中數據的各種格式
[java] view plain
//讀取excel
try {
request.setCharacterEncoding("gbk");
response.setContentType("text/html;charset=gbk");
// 1. 創建工廠類
DiskFileItemFactory factory = new DiskFileItemFactory();
// 2. 創建FileUpload對象
ServletFileUpload upload = new ServletFileUpload(factory);

// 3. 判斷是否是上傳表單
// boolean b = upload.isMultipartContent(request);
// 設置上傳文件最大值
upload.setSizeMax(25 * 1024 * 1024);
// 是文件上傳表單
// 4. 解析request,獲得FileItem項
List<FileItem> fileitems = upload.parseRequest(request);
// 5. 遍歷集合
for (FileItem item : fileitems) {
// 判斷是不是普通欄位
if (!item.isFormField()) {
// 獲得流,讀取數據寫入文件
InputStream in = item.getInputStream();
Workbook book = createWorkBook(in,item.getName());
// 獲得第一個工作表對象
Sheet sheet = book.getSheetAt(0);
if(0==sheet.getLastRowNum()){
//如果沒有數據
request.setAttribute("message", "excel的sheet0中不存在數據");
request.getRequestDispatcher("/cc/util/excelToData.jsp").forward(request, response);
}

// 第一行為標題,從第二行開始錄入
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
//標題行,用來對比方便得到數據
Row titleRow = sheet.getRow(0);
//數據行
Row row = sheet.getRow(i);
//獲得值
String value_temp= this.getValue((Cell) row.getCell(2));
}
}
}

} catch (Exception e) {
e.printStackTrace();
message="導入失敗<br/>"+message;
request.setAttribute("message",message);
request.getRequestDispatcher("/cc/util/excelToData.jsp").forward(request, response);

}

③ 用POI將EXCEL表的數據導入到資料庫時的setCellType()問題。

你需要先判斷value的類型,然後再經過相應的處理後,再獲取和使用它。
具體 value 的類型:
Cell.CELL_TYPE_STRING
Cell.CELL_TYPE_NUMERIC
Cell.CELL_TYPE_FORMULA
Cell.CELL_TYPE_BOOLEAN
Cell.CELL_TYPE_BLANK
Cell.CELL_TYPE_ERROR
希望對你有幫助。

④ poi導入excel

方法/步驟

  • 一,ExcelUtils工具類(也就是解析EXCEL文件,判斷EXCEL的類型以及數據的類型)

  • importjava.io.IOException;

    importjava.io.InputStream;

    importjava.math.BigDecimal;

    importjava.text.SimpleDateFormat;

    importjava.util.ArrayList;

    importjava.util.Date;

    importjava.util.List;

    importorg.apache.poi.hssf.usermodel.HSSFDateUtil;

    importorg.apache.poi.hssf.usermodel.HSSFWorkbook;

    importorg.apache.poi.ss.usermodel.Cell;

    importorg.apache.poi.ss.usermodel.Row;

    importorg.apache.poi.ss.usermodel.Sheet;

    importorg.apache.poi.ss.usermodel.Workbook;

    importorg.apache.poi.xssf.usermodel.XSSFWorkbook;

    public class ExcelUtils {

    privatefinalstaticString excel2003L =「.xls」;// 2003-版本的excel

    privatefinalstaticString excel2007U =「.xlsx」;// 2007 +版本的excel

    / **

    *描述:獲取IO流中的數據,組裝成List <List <Object>對象

    * @param in,fileName

    * @返回

    * @throws IOException

    * /

    publicList <List <Object> getBankListByExcel(InputStream in,String fileName)throwsException {

    列表<List <Object> list =null;

    //創建的Excel工作薄

    Workbook work =this.getWorkbook(in,fileName);

    if(null== work){

    拋出新的異常(「創建Excel工作薄為空!」);

    }

    Sheet sheet =null;//頁數

    行row =null;//行數

    Cell cell =null;//列數

    list =newArrayList <List <Object >>();

    //遍歷的Excel中所有的片

    for(inti =0; i <work.getNumberOfSheets(); i ++){

    sheet = work.getSheetAt(i);

    if(sheet ==null){continue;}

    //遍歷當前片中的所有行

    for(intj = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j ++){

    row = sheet.getRow(j);

    if(row ==null|| row.getFirstCellNum()== j){continue;}

    //遍歷所有的列

    列表<Object> li =newArrayList <Object>();

    for(inty = row.getFirstCellNum(); y <row.getLastCellNum(); y ++){

    cell = row.getCell(y);

    li.add(this.getValue(cell));

    }

    list.add(LI);

    }

    }

    return 單

    }

    / **

    *描述:根據文件後綴,自適應上傳文件的版本

    * @param inStr,fileName

    * @返回

    * @throws異常

    * /

    publicWorkbook getWorkbook(InputStream inStr,String fileName)throwsException {

    工作簿wb =null;

    String fileType = fileName.substring(fileName.lastIndexOf(「。」));

    if(excel2003L.equals(fileType)){

    wb =newHSSFWorkbook(inStr);// 2003-

    }elseif(excel2007U.equals(fileType)){

    wb =newXSSFWorkbook(inStr);// 2007 +

    }else{

    拋出新的異常(「解析的文件格式有誤!」);

    }

    返回wb;

    }

    / **

    *描述:對表格中數值進行格式化

    * @param單元格

    * @返回

    * /

    //解決擅長類型問題,獲得數值

    publicString getValue(Cell cell){

    String value =「」;

    if(null== cell){

    返回值

    }

    switch(cell.getCellType()){

    //數值型

    案例Cell.CELL_TYPE_NUMERIC:

    if(HSSFDateUtil.isCellDateFormatted(cell)){

    //如果是date類型則,獲取該單元格的日期值

    Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());

    SimpleDateFormat format =newSimpleDateFormat(「yyyy-MM-dd」);

    value = format.format(date);;

    }else{//純數字

    BigDecimal big =newBigDecimal(cell.getNumericCellValue());

    value = big.toString();

    //解決1234.0去掉後面的.0

    if(null!= value &&!「」.equals(value.trim())){

    String [] item = value.split(「[。]」);

    if(1<item.length &&「0」.equals(item [1])){

    value = item [0];

    }

    }

    }

    break;

    //字元串類型

    案例Cell.CELL_TYPE_STRING:

    value = cell.getStringCellValue()。toString();

    break;

    //公式類型

    案例Cell.CELL_TYPE_FORMULA:

    //讀公式計算值

    value = String.valueOf(cell.getNumericCellValue());

    if(value.equals(「NaN」)){//如果獲取的數據值為非法值,則轉換為獲取字元串

    value = cell.getStringCellValue()。toString();

    }

    break;

    //布爾類型

    案例Cell.CELL_TYPE_BOOLEAN:

    value =「」+ cell.getBooleanCellValue();

    break;

    默認值:

    value = cell.getStringCellValue()。toString();

    }

    if(「null」.endsWith(value.trim())){

    value =「」;

    }

    返回值

    }

    }

  • 二,定義兩個實體類,一個是對於的Excel文件,解析它的數據(ExcelBean),另一個是導入資料庫表的實體類(人)

    ExcelBean.java

  • <strong> <span style =「font-size:18px;」>importorg.apache.poi.xssf.usermodel.XSSFCellStyle;

    公共類ExcelBean實現java.io.Serializable {

    privateString headTextName;//列頭(標題)名

    privateString propertyName;//對應欄位名

    私有整數列;//合並單元格數

    私人XSSFCellStyle cellStyle;

    publicExcelBean(){

    }

    publicExcelBean(String headTextName,String propertyName){

    這個.headTextName = headTextName;

    這個.propertyName = propertyName;

    }

    publicExcelBean(String headTextName,String propertyName,Integer cols){

    super();

    這個.headTextName = headTextName;

    這個.propertyName = propertyName;

    這個.cols = cols;

    }

    publicString getHeadTextName(){

    returnheadTextName;

    }

    publicvoidsetHeadTextName(String headTextName){

    這個.headTextName = headTextName;

    }

    publicString getPropertyName(){

    returnpropertyName;

    }

    publicvoidsetPropertyName(String propertyName){

    這個.propertyName = propertyName;

    }

    publicInteger getCols(){

    返回列;

    }

    公共無效setCols(Integer cols){

    這個.cols = cols;

    }

    上市XSSFCellStyle getCellStyle(){

    返回cellStyle;

    }

    公共無效setCellStyle(XSSFCellStyle cellStyle){

    這個.cellStyle = cellStyle;

    }

    } </ span> </ strong>

  • people.java

  • importjava.util.Date;

    公共課人

    私有整數id

    privateString userName;

    私人字元串密碼;

    私人整數年齡;

    私人日期;

    publicInteger getId(){

    返回id

    }

    publicvoidsetId(Integer id){

    這個.id = id;

    }

    publicString getUserName(){

    returnuserName;

    }

    publicvoidsetUserName(String userName){

    這個.userName = userName ==null?null:userName.trim();

    }

    publicString getPassword(){

    返回密碼

    }

    publicvoidsetPassword(String password){

    這個.password = password ==null?null:password.trim();

    }

    publicInteger getAge(){

    回歸年齡

    }

    publicvoidsetAge(Integer age){

    這個.age = age

    }

    publicDate getDate(){

    退貨日期

    }

    publicvoidsetDate(Date date){

    這個.date = date

    }

    }

⑤ java通過poi把excel文件導入mysql資料庫報錯

java通過poi把excel文件導入mysql資料庫報錯是因為excel中的數據類型要跟mysql中的數據類型和長度對應,否則類型轉換異常是最常見的。所以插入到mysql資料庫的時候需要做類型檢查。

1、Excel中的測試數據:

⑥ 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導入到資料庫

用到的類 是 :
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

try {
// List<String[]> 中的元素 行數組String[]為excel中的每一行
List<String[]> list = new ArrayList<String[]>();
InputStream is = new FileInputStream("test.xls");
HSSFWorkbook hwk = new HSSFWorkbook(is);// 將is流實例到 一個excel流里
HSSFSheet sh = hwk.getSheetAt(0);// 得到book第一個工作薄sheet
int rows = sh.getLastRowNum()+1 - sh.getFirstRowNum(); // 總行數
for(int i=0; i<rows; i++){
HSSFRow row = sh.getRow(i);
int cols = row.getLastCellNum()+1 - row.getFirstCellNum(); // 該行的總列數
String[] str = new String[cols]; // 用來存放該行每一列的值
for (int j = 0; j < cols; j++) {
Object col = row.getCell((short)j);
str[j] = col.toString();
}
}
......
......
循環變數 i 和 j 可以自己設定從第幾行開始讀,第幾列開始讀,下標從0開始。
然後你想做什麼判斷想做什麼數據匹配都可以自己加了。
poi.hssf.usermodel.* jar包要是網上找不到,就給我發郵件,我郵給你:[email protected]

⑧ 用poi怎樣把excel文件裡面的數據導入資料庫三張關聯的表中

package bis.excel;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import jxl.Sheet;
import jxl.Workbook;
public class Excel {

@SuppressWarnings("unchecked")
public List addCust(File file){
List list=new ArrayList();
List list2=new ArrayList();
Workbook rwb=null;
try {
List list1=new ArrayList();

InputStream is=new FileInputStream(file);//讀取文件(所要導入excel的保存目錄,如:f:\\a.xls)
rwb=Workbook.getWorkbook(is);//創建工作薄
Sheet rs=rwb.getSheet(0);//讀取excel中的第一個工作表(默認新建excel下面有sheet1,sheet2,sheet3)
int cellCount=rs.getColumns();//獲取Sheet表中所包含的總列數
int rowCount=rs.getRows();//獲取Sheet表中所包含的總行數
for(int m=0;m<cellCount;m++){//將表的第一行數據保存到list1中(列名),即id,name ,age
String cell=rs.getCell(m,0).getContents();
list1.add(cell);
}
for(int i=1;i<rowCount;i++){//獲取值
Map map=new TreeMap();
for(int j=0;j<cellCount;j++){
map.put(list1.get(j),rs.getCell(j,i).getContents());//將值以鍵/值對方式保存到map對象中即(id:1,name:zhangsan,age:18)
}
list.add(map);//將值保存到list中
//System.out.println(list.get(i-1));
}

list2.add(list1);//將表頭(id,name,age)保存到list2中
list2.add(list);//將值保存到list2中
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
rwb.close();
}
return list2;
}
public void tosql(){
List list=addCust(file);//file:所要導入excel的保存目錄,如:f:\\a.xls
Map map=new HashMap();
String[] values=new String[ls2.size()];//保存id,name,age 值
for (int i =0; i < ls2.size(); i++) {
map=(Map)ls2.get(i);
String value="";
id=(String)map.get("id");
name=(String)map.get("name");
age=(String)map.get("age");
value=id+";"+name+";"+age;
values[i]=value;
}
}
}
這是段讀取excel表數據的代碼,在tosql方法中調用addCust方法讀取excel表,最後把所有行的id,name,age值保存到了values數組中,也可以保存到類中,如果你會對資料庫操作的話,
後面的你自己弄下就行了,不會的話留言,我晚上在告訴你,我現在上班呢,時間有限,只能寫這么多了

熱點內容
c語言八進制十六進制 發布:2025-05-15 08:22:17 瀏覽:282
華為安卓如何更新鴻蒙 發布:2025-05-15 08:18:52 瀏覽:373
工商密碼器是什麼 發布:2025-05-15 08:18:50 瀏覽:751
c語言自考 發布:2025-05-15 07:52:42 瀏覽:501
壓縮的玉 發布:2025-05-15 07:51:22 瀏覽:790
android的控制項 發布:2025-05-15 07:50:36 瀏覽:553
南崗法院伺服器ip地址 發布:2025-05-15 07:46:02 瀏覽:288
實況如何退出賬號安卓 發布:2025-05-15 07:45:56 瀏覽:919
深入編譯器 發布:2025-05-15 07:41:35 瀏覽:879
電信手機號服務密碼怎麼查 發布:2025-05-15 07:40:10 瀏覽:614