你好:
Java代碼
1.<%@page language="java" contentType="text/html; charset=utf-8" %>
2.<%@page import="java.io.File"%>
3.<%@page import="java.io.InputStream"%>
4.<%@page import="java.io.FileInputStream"%>
5.<%@page import="java.util.Vector"%>
6.<%@page import="java.util.Iterator"%>
7.<%@page import="org.apache.poi.hssf.usermodel.HSSFWorkbook"%>
8.<%@page import="org.apache.poi.hssf.usermodel.HSSFSheet"%>
9.<%@page import="org.apache.poi.hssf.usermodel.HSSFRow"%>
10.<%@page import="org.apache.poi.hssf.usermodel.HSSFCell"%>
11.<%@page import="org.apache.poi.poifs.filesystem.POIFSFileSystem"%>
12.<%@page import="com.fuyun.hp.common.PubUtil"/>
13.<%@page import="com.fuyun.hp.hibernate.mapping.RadioType"%>
14.<%@page import="com.fuyun.hp.hibernate.mapping.RadioTypeDAO"%>
15.<%@page import="com.fuyun.hp.common.SpringContext"/>
16.<%@page import="org.springframework.orm.hibernate3.HibernateTransactionManager"/>
17.<%@page import="org.springframework.transaction.TransactionDefinition"/>
18.<%@page import="org.springframework.transaction.TransactionStatus"/>
19.<%@page import="org.springframework.transaction.support.DefaultTransactionDefinition"/>
20.<%
21.//出於考慮顯示格式,實際運行時,請將代碼中的全形空格轉換為半形空格
22.//代碼中的PubUtil.nvl(Object)方法,當Object為null時返回空串(也就是類似Oracle中的nvl方法)
23.request.setCharacterEncoding("utf-8");
24.File tempPath = new File(getServletContext().getRealPath("/")
25.+ AdsUtil.TEMP_UPLOAD_PATH);
26.if (!tempPath.exists())
27.return;
28.
29.String fileName = "radioTree.xls";
30.fileName = tempPath.toString() + "\\" + fileName;
31.InputStream inp = new FileInputStream(fileName);
32.HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(inp));
33.HSSFSheet sheet = wb.getSheetAt(0);
34.RadioType rt;
35.RadioTypeDAO rtDao = RadioTypeDAO.getInstance();
36.
37.HibernateTransactionManager tManager = SpringContext.getTransactionManager();
38.TransactionDefinition td = new DefaultTransactionDefinition();
39.TransactionStatus ts = tManager.getTransaction(td);
40.
41.for (Iterator<HSSFRow> rit = (Iterator<HSSFRow>)sheet.rowIterator(); rit.hasNext(); ) {
42.HSSFRow row = rit.next();
43.boolean existFlag = true;
44.for(short index = 0;index < row.getPhysicalNumberOfCells();index ++){
45.HSSFCell cell = row.getCell(index);
46.if(index == row.getLastCellNum() && cell == null)
47.existFlag = false;
48.else if(index < row.getLastCellNum() && cell == null)
49.continue;
50.else
51.break;
52.}
53.if(existFlag == false){
54.break;
55.}
56.else{
57.Vector<String> values = new Vector<String>();
58.rt = null;
59.try{
60.if(row.getRowNum() == 0)//從第2行開始讀取
61.continue;
62.for (int index = 0; index < 5; index ++) {
63.HSSFCell cell = row.getCell(new Short(index + ""));
64.if(cell == null)
65.values.add("");
66.else{
67.if(cell.getCellType() == cell.CELL_TYPE_NUMERIC){
68.values.add(String.format("%.0f", cell.getNumericCellValue()));
69.}
70.else
71.values.add(PubUtil.nvl(cell.getStringCellValue()));
72.}
73.}
74.
75.if("".equals(PubUtil.nvl(values.get(0)))){
76.rt = new RadioType();
77.}
78.else{
79.rt = rtDao.get(values.get(0));
80.}
81.rt.setId(values.get(0));//id
82.rt.setParentId(PubUtil.nvl(values.get(1)));//上級id
83.rt.setName(PubUtil.nvl(values.get(2)));//名稱
84.rt.setType(PubUtil.nvl(values.get(3)));//類型
85.rt.setOrderIndex(Integer.parseInt(PubUtil.nvl(values.get(4))));//排序
86.
87.if("".equals(PubUtil.nvl(values.get(0)))){
88.rtDao.save(rt);
89.}
90.else{
91.rtDao.update(rt);
92.}
93.out.println(rt);
94.}
95.catch(Exception e){
96.tManager.rollback(ts);
97.e.printStackTrace();
98.out.print("{success: false, info:'導入失敗!'}");
99.return;
100.}
101.}
102.}
103.tManager.commit(ts);
104.out.print("{success: true}");
105. %>
Ⅱ java使用什麼技術實現excel數據的批量導入導出
java使用第三方工具包POI技術實現excel數據的批量導入導出。
舉例如下:
1、下載apache的相關jar包。poi-ooxml-3.6.jar xmlbeans-2.3.0.jar等,如圖:
2、編寫相關的讀寫類
/**
* 讀取xls文件內容
*/
private
List<XlsDto> readXls() throws
IOException {
InputStream is = new
FileInputStream("test.xls");
HSSFWorkbook hssfWorkbook = new
HSSFWorkbook(is);
XlsDto xlsDto = null;
List<XlsDto> list = new
ArrayList<XlsDto>();
// 循環工作表Sheet
for
(int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
if
(hssfSheet == null) {
continue;
}
// 循環行Row
for
(int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
HSSFRow hssfRow = hssfSheet.getRow(rowNum);
if
(hssfRow == null) {
continue;
}
xlsDto = new
XlsDto();
// 循環列Cell
// 0學號 1姓名 2學院 3課程名 4 成績
// for (int cellNum = 0; cellNum <=4; cellNum++) {
HSSFCell xh = hssfRow.getCell(0);
if
(xh == null) {
continue;
}
xlsDto.setXh(getValue(xh));
HSSFCell xm = hssfRow.getCell(1);
if
(xm == null) {
continue;
}
xlsDto.setXm(getValue(xm));
HSSFCell yxsmc = hssfRow.getCell(2);
if
(yxsmc == null) {
continue;
}
xlsDto.setYxsmc(getValue(yxsmc));
HSSFCell kcm = hssfRow.getCell(3);
if
(kcm == null) {
continue;
}
xlsDto.setKcm(getValue(kcm));
HSSFCell cj = hssfRow.getCell(4);
if
(cj == null) {
continue;
}
xlsDto.setCj(Float.parseFloat(getValue(cj)));
list.add(xlsDto);
}
}
return
list;
}
3、導出就是輸入到一個新的excel文件裡面
public void writeXls(List<Student> list, String path) throws Exception {
if (list == null) {原始數據為空,直接返回
return;
}
int countColumnNum = list.size();//設置列數
HSSFWorkbook book = new HSSFWorkbook(); //創建工作表對象
HSSFSheet sheet = book.createSheet("studentSheet");
// 創建第一行
HSSFRow firstRow = sheet.createRow(0);
HSSFCell[] firstCells = new HSSFCell[countColumnNum];
//創建表頭
String[] options = { "no", "name", "age", "score" };
//循環數據域
for (int j = 0; j < options.length; j++) {
firstCells[j] = firstRow.createCell(j);
firstCells[j].setCellValue(new HSSFRichTextString(options[j]));
}
//處理每一個cell的值
for (int i = 0; i < countColumnNum; i++) {
HSSFRow row = sheet.createRow(i + 1);
Student student = list.get(i);
for (int column = 0; column < options.length; column++) {
HSSFCell no = row.createCell(0);
HSSFCell name = row.createCell(1);
HSSFCell age = row.createCell(2);
HSSFCell score = row.createCell(3);
no.setCellValue(student.getNo());
name.setCellValue(student.getName());
age.setCellValue(student.getAge());
score.setCellValue(student.getScore());
}
}
File file = new File(path);
OutputStream os = new FileOutputStream(file);
System.out.println(Common.WRITE_DATA + path);
book.write(os);
os.close();
}
Ⅲ java通過poi把excel文件導入mysql資料庫報錯
java通過poi把excel文件導入mysql資料庫報錯是因為excel中的數據類型要跟mysql中的數據類型和長度對應,否則類型轉換異常是最常見的。所以插入到mysql資料庫的時候需要做類型檢查。
1、Excel中的測試數據:
Ⅳ 求助:怎麼用一個Java程序實現Excel數據導入
做過一個項目中EXCEL導入是純JAVA程序寫的,但是比較繁瑣。自定義了一個XML文件,通過XML文件配置導入數據欄位的約束和關系。例如,主鍵、外鍵、是否允許為空等約束,通過此列對應資料庫某個表中相應的主鍵,及聯合主鍵,各列之間的關系等都考慮在內。通過JDOM解析XML文件,迭代後取相當的值判斷,生成導入錯誤文件。正確時保存入資料庫,返回前台信息。
Ⅳ java web 怎麼導入excel文件
1.要正確的將Web客戶端的Excel文件導入到伺服器的資料庫中,需要將客戶端的Excel文件上傳到伺服器上。可以使用FileUpload控制項完成。2.Excel文件上傳到伺服器指定的目錄中,這里假設是該站點的upfiles目錄中。3.使用SQL語句從upfiles目錄中的上傳Excel文件中讀取數據顯示或寫入資料庫。
Ⅵ java中怎麼把excel導入資料庫
1、加入依賴的jar文件:
引用:
*mysql的jar文件
*Spring_HOME/lib/poi/*.jar
2、編寫資料庫鏈接類
packagecom.zzg.db;
importjava.sql.Connection;
importjava.sql.DriverManager;
publicclassDbUtils{
privatestaticConnectionconn;
static{
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost/test","root","123456");
}catch(Exceptione){
e.printStackTrace();
}
}
publicstaticConnectiongetConn(){
returnconn;
}
publicstaticvoidsetConn(Connectionconn){
DbUtils.conn=conn;
}
}
3、編寫資料庫操作類
packagecom.zzg.db;
importjava.sql.Connection;
importjava.sql.PreparedStatement;
importjava.sql.SQLException;
publicclassExcuteData{
privatePreparedStatementpstmt;
publicbooleanExcuData(Stringsql){
Connectionconn=DbUtils.getConn();
booleanflag=false;
try{
pstmt=conn.prepareStatement(sql);
flag=pstmt.execute();
}catch(SQLExceptione){
e.printStackTrace();
}
returnflag;
}
}
4、編寫Excel表格實體類
packagecom.zzg.model;
publicclassTableCell{
privateString_name;
privateString_value;
publicStringget_name(){
return_name;
}
publicvoidset_name(String_name){
this._name=_name;
}
publicStringget_value(){
return_value;
}
publicvoidset_value(String_value){
this._value=_value;
}
}
5、編寫主鍵生成方法
packagecom.zzg.util;
importjava.text.SimpleDateFormat;
importjava.util.Date;
importjava.util.Random;
publicclassGenericUtil{
()
{
StringprimaryKey;
primaryKey=newSimpleDateFormat("yyyyMMddHHmmss").format(newDate());
Randomr=newRandom();
primaryKey+=r.nextInt(100000)+100000;
returnprimaryKey;
}
}
6、編寫Excel操作類
packagecom.zzg.deployData;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.Serializable;
importjava.util.ArrayList;
importjava.util.List;
importorg.apache.poi.hssf.usermodel.HSSFCell;
importorg.apache.poi.hssf.usermodel.HSSFRow;
importorg.apache.poi.hssf.usermodel.HSSFSheet;
importorg.apache.poi.hssf.usermodel.HSSFWorkbook;
importcom.zzg.db.ExcuteData;
importcom.zzg.model.TableCell;
importcom.zzg.util.GenericUtil;
publicclassOperExcel<TextendsSerializable>{
privateHSSFWorkbookworkbook;
privateStringtableName;
privateClass<T>type;
privateStringsheetName;
publicOperExcel(FileexcelFile,StringtableName,Class<T>type,
StringsheetName)throwsFileNotFoundException,
IOException{
workbook=newHSSFWorkbook(newFileInputStream(excelFile));
this.tableName=tableName;
this.type=type;
this.sheetName=sheetName;
InsertData();
}
//向表中寫入數據
publicvoidInsertData(){
System.out.println("yyy");
ExcuteDataexcuteData=newExcuteData();
List<List>datas=getDatasInSheet(this.sheetName);
//向表中添加數據之前先刪除表中數據
StringstrSql="deletefrom"+this.tableName;
excuteData.ExcuData(strSql);
//拼接sql語句
for(inti=1;i<datas.size();i++){
strSql="insertinto"+this.tableName+"(";
Listrow=datas.get(i);
for(shortn=0;n<row.size();n++){
TableCellexcel=(TableCell)row.get(n);
if(n!=row.size()-1)
strSql+=excel.get_name()+",";
else
strSql+=excel.get_name()+")";
}
strSql+="values(";
for(shortn=0;n<row.size();n++){
TableCellexcel=(TableCell)row.get(n);
try{
if(n!=row.size()-1){
strSql+=getTypeChangeValue(excel)+",";
}else
strSql+=getTypeChangeValue(excel)+")";
}catch(RuntimeExceptione){
e.printStackTrace();
}catch(Exceptione){
e.printStackTrace();
}
}
//執行sql
excuteData.ExcuData(strSql);
}
}
/**
*獲得表中的數據
*@paramsheetName表格索引(EXCEL是多表文檔,所以需要輸入表索引號)
*@return由LIST構成的行和表
*/
publicList<List>getDatasInSheet(StringsheetName){
List<List>result=newArrayList<List>();
//獲得指定的表
HSSFSheetsheet=workbook.getSheet(sheetName);
//獲得數據總行數
introwCount=sheet.getLastRowNum();
if(rowCount<1){
returnresult;
}
//逐行讀取數據
for(introwIndex=0;rowIndex<rowCount;rowIndex++){
//獲得行對象
HSSFRowrow=sheet.getRow(rowIndex);
if(row!=null){
List<TableCell>rowData=newArrayList<TableCell>();
//獲得本行中單元格的個數
intcolumnCount=sheet.getRow(0).getLastCellNum();
//獲得本行中各單元格中的數據
for(shortcolumnIndex=0;columnIndex<columnCount;columnIndex++){
HSSFCellcell=row.getCell(columnIndex);
//獲得指定單元格中數據
ObjectcellStr=this.getCellString(cell);
TableCellTableCell=newTableCell();
TableCell.set_name(getCellString(
sheet.getRow(0).getCell(columnIndex)).toString());
TableCell.set_value(cellStr==null?"":cellStr
.toString());
rowData.add(TableCell);
}
result.add(rowData);
}
}
returnresult;
}
/**
*獲得單元格中的內容
*
*@paramcell
*@returnresult
*/
protectedObjectgetCellString(HSSFCellcell){
Objectresult=null;
if(cell!=null){
intcellType=cell.getCellType();
switch(cellType){
caseHSSFCell.CELL_TYPE_STRING:
result=cell.getStringCellValue();
break;
caseHSSFCell.CELL_TYPE_NUMERIC:
result=cell.getNumericCellValue();
break;
caseHSSFCell.CELL_TYPE_FORMULA:
result=cell.getNumericCellValue();
break;
caseHSSFCell.CELL_TYPE_ERROR:
result=null;
break;
caseHSSFCell.CELL_TYPE_BOOLEAN:
result=cell.getBooleanCellValue();
break;
caseHSSFCell.CELL_TYPE_BLANK:
result=null;
break;
}
}
returnresult;
}
//根據類型返回相應的值
@SuppressWarnings("unchecked")
(TableCellexcelElement)
throwsRuntimeException,Exception{
StringcolName=excelElement.get_name();
StringcolValue=excelElement.get_value();
StringretValue="";
if(colName.equals("id")){
retValue="'"+GenericUtil.getPrimaryKey()+"'";
returnretValue;
}
if(colName==null){
retValue=null;
}
if(colName.equals("class_createuser")){
retValue="yaa101";
return"'"+retValue+"'";
}
retValue="'"+colValue+"'";
returnretValue;
}
}
7、編寫調用操作Excel類的方法
packagecom.zzg.deployData;
importjava.io.File;
importjava.io.FileNotFoundException;
importjava.io.IOException;
publicclassDeployData{
privateFilefileOut;
publicvoidexcute(Stringfilepath){
fileOut=newFile(filepath);
this.deployUserInfoData();
}
publicvoiddeployUserInfoData(){
try{
newOperExcel(fileOut,"test",Object.class,"Sheet1");
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
8、編寫客戶端
packagecom.zzg.client;
importcom.zzg.deployData.DeployData;
publicclassDeployClient{
publicstaticvoidmain(String[]args){
DeployDatadeployData=newDeployData();
deployData.excute("D://test.xls");
}
}
Ⅶ 如何用Java將excel數據導入資料庫
public static void main(String args[]) throws BiffException, IOException, WriteException{
//1 從Excel文件讀取數據表
//Java Excel API既可以從本地文件系統的一個文件(.xls),也可以從輸入流中讀取Excel數據表。
//讀取Excel數據表的第一步是創建Workbook(術語:工作薄),下面的代碼片段舉例說明了應該如何操作:
//(完整代碼見ExcelReading.java)
try
{
//構建Workbook對象, 只讀Workbook對象
//直接從本地文件創建Workbook
//從輸入流創建Workbook
InputStream is = new FileInputStream("D:/user.xls");
jxl.Workbook rwb = Workbook.getWorkbook(is);
//一旦創建了Workbook,我們就可以通過它來訪問Excel Sheet(術語:工作表)。參考下面的代碼片段:
//獲取第一張Sheet表
Sheet rs = (Sheet) rwb.getSheet(0);
//我們既可能通過Sheet的名稱來訪問它,也可以通過下標來訪問它。如果通過下標來訪問的話,
//要注意的一點是下標從0開始,就像數組一樣。
//一旦得到了Sheet,我們就可以通過它來訪問Excel Cell(術語:單元格)。參考下面的代碼片段:
//獲取第一行,第一列的值
Cell c00 = ((jxl.Sheet) rs).getCell(0, 0);
String strc00 = c00.getContents();
//獲取第一行,第二列的值
Cell c10 = ((jxl.Sheet) rs).getCell(1, 0);
String strc10 = c10.getContents();
//獲取第二行,第二列的值
Cell c11 = ((jxl.Sheet) rs).getCell(1, 1);
String strc11 = c11.getContents();
System.out.println("Cell(0, 0)" + " value : " + strc00 + "; type : " + c00.getType());
System.out.println("Cell(1, 0)" + " value : " + strc10 + "; type : " + c10.getType());
System.out.println("Cell(1, 1)" + " value : " + strc11 + "; type : " + c11.getType());
//如果僅僅是取得Cell的值,我們可以方便地通過getContents()方法,
//它可以將任何類型的Cell值都作為一個字元串返回。示例代碼中Cell(0, 0)是文本型,
//Cell(1, 0)是數字型,Cell(1,1)是日期型,通過getContents(),三種類型的返回值都是字元型。
//如果有需要知道Cell內容的確切類型,API也提供了一系列的方法。參考下面的代碼片段:
String strcc00 = null;
double strcc10 = 0.00;
Date strcc11 = null;
Cell cc00 = ((jxl.Sheet) rs).getCell(0, 0);
Cell cc10 = ((jxl.Sheet) rs).getCell(1, 0);
Cell cc11 = ((jxl.Sheet) rs).getCell(1, 1);
if(c00.getType() == CellType.LABEL)
{
LabelCell labelc00 = (LabelCell)cc00;
strcc00 = labelc00.getString();
}
if(c10.getType() == CellType.NUMBER)
{
NumberCell numc10 = (NumberCell)cc10;
strcc10 = numc10.getValue();
}
if(c11.getType() == CellType.DATE)
{
DateCell datec11 = (DateCell)cc11;
strcc11 = datec11.getDate();
}
System.out.println("Cell(0, 0)" + " value : " + strcc00 + "; type : " + cc00.getType());
System.out.println("Cell(1, 0)" + " value : " + strcc10 + "; type : " + cc10.getType());
System.out.println("Cell(1, 1)" + " value : " + strcc11 + "; type : " + cc11.getType());
//在得到Cell對象後,通過getType()方法可以獲得該單元格的類型,然後與API提供的基本類型相匹配,
//強制轉換成相應的類型,最後調用相應的取值方法getXXX(),就可以得到確定類型的值。
//API提供了以下基本類型,與Excel的數據格式相對應,如下圖所示:
//每種類型的具體意義,請參見Java Excel API Document。
//當你完成對Excel電子表格數據的處理後,一定要使用close()方法來關閉先前創建的對象,
//以釋放讀取數據表的過程中所佔用的內存空間,在讀取大量數據時顯得尤為重要。參考如下代碼片段:
//操作完成時,關閉對象,釋放佔用的內存空間
rwb.close();
}
catch (Exception e)
{
e.printStackTrace();
}
//Java Excel API提供了許多訪問Excel數據表的方法,在這里我只簡要地介紹幾個常用的方法,
//其它的方法請參考附錄中的Java Excel API Document。
//Workbook類提供的方法
//1. int getNumberOfSheets();
//獲得工作薄(Workbook)中工作表(Sheet)的個數,示例:
jxl.Workbook rwb = jxl.Workbook.getWorkbook(new File("D:/user.xls"));
int sheets = rwb.getNumberOfSheets();
//2. Sheet[] getSheets();
//返回工作薄(Workbook)中工作表(Sheet)對象數組,示例:
jxl.Workbook rwb2 = jxl.Workbook.getWorkbook(new File("D:/user.xls"));
Sheet[] sheets2 = (Sheet[]) rwb2.getSheets();
//3. String getVersion();
//返回正在使用的API的版本號,好像是沒什麼太大的作用。
jxl.Workbook rwb3 = jxl.Workbook.getWorkbook(new File("D:/user.xls"));
String apiVersion = rwb3.getVersion();
//Sheet介面提供的方法
//1) String getName();
//獲取Sheet的名稱,示例:
jxl.Workbook rwb4 = jxl.Workbook.getWorkbook(new File("D:/user.xls"));
jxl.Sheet rs = rwb4.getSheet(0);
String sheetName = rs.getName();
//2) int getColumns()
//獲取Sheet表中所包含的總列數,示例:
jxl.Workbook rwb5 = jxl.Workbook.getWorkbook(new File("D:/user.xls"));
jxl.Sheet rs2 = rwb5.getSheet(0);
int rsColumns = rs2.getColumns();
//3) Cell[] getColumn(int column)
//獲取某一列的所有單元格,返回的是單元格對象數組,示例:
jxl.Workbook rwb6 = jxl.Workbook.getWorkbook(new File("D:/user.xls"));
jxl.Sheet rs3 = rwb6.getSheet(0);
Cell[] cell = rs3.getColumn(0);
//4) int getRows()
//獲取Sheet表中所包含的總行數,示例:
jxl.Workbook rwb7 = jxl.Workbook.getWorkbook(new File("D:/user.xls"));
jxl.Sheet rs4 = rwb7.getSheet(0);
int rsRows = rs4.getRows();
//5) Cell[] getRow(int row)
//獲取某一行的所有單元格,返回的是單元格對象數組,示例子:
jxl.Workbook rwb8 = jxl.Workbook.getWorkbook(new File("D:/user.xls"));
jxl.Sheet rs5 = rwb8.getSheet(0);
Cell[] cell5 = rs5.getRow(0);
//6) Cell getCell(int column, int row)
//獲取指定單元格的對象引用,需要注意的是它的兩個參數,第一個是列數,第二個是行數,
//這與通常的行、列組合有些不同。
jxl.Workbook rwb9 = jxl.Workbook.getWorkbook(new File("D:/user.xls"));
jxl.Sheet rs6 = rwb9.getSheet(0);
Cell cell6 = rs6.getCell(0, 0);