不会写,求高手代码实现!
可以的话,再加一个测试main方法
可参考如下:
public class Test3{
public static void main(String[] args) throws Exception {
Workbook workbook=null;
String columnName[] = {"姓名","年龄","住址"};
for(int i=0;i System.err.print(columnName[i]+"\t");
}
System.out.println();
Sheet sheet=null;
TreeMap map = new TreeMap();
InputStream input=new FileInputStream("D://tt.xls");
workbook =Workbook.getWorkbook(input);
sheet=workbook.getSheet(0);
for (int i = 0; i <sheet.getColumns(); i++) {
String []str=new String[sheet.getRows()];
for (int j = 0; j <sheet.getRows(); j++) {
Cell cell=sheet.getCell(i,j);
str[j]=cell.getContents();
}
map.put(columnName[i], str);
}
for (int i = 0, j=0; i<map.get(columnName[j]).length; i++) {
for ( j = 0; j < map.size(); j++) {
System.out.print(map.get(columnName[j])[i]+"\t");
}
j=0;
System.out.println();
}
}
}
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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.poifs.filesystem.POIFSFileSystem;
public class ExcelOperate {
public static void main(String[] args) throws Exception {
File file = new File("ExcelDemo.xls");
String[][] result = getData(file, 1);
int rowLength = result.length;
for(int i=0;i<rowLength;i++) {
for(int j=0;j<result[i].length;j++) {
System.out.print(result[i][j]+"\t\t");
}
System.out.println();
}
}
/**
* 读取Excel的内容,第一维数组存储的是一行中格列的值,二维数组存储的是多少个行
* @param file 读取数据的源Excel
* @param ignoreRows 读取数据忽略的行数,比喻行头不需要读入 忽略的行数为1
* @return 读出的Excel中数据的内容
* @throws FileNotFoundException
* @throws IOException
*/
public static String[][] getData(File file, int ignoreRows)
throws FileNotFoundException, IOException {
List<String[]> result = new ArrayList<String[]>();
int rowSize = 0;
BufferedInputStream in = new BufferedInputStream(new FileInputStream(
file));
// 打开HSSFWorkbook
POIFSFileSystem fs = new POIFSFileSystem(in);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFCell cell = null;
for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
HSSFSheet st = wb.getSheetAt(sheetIndex);
// 第一行为标题,不取
for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {
HSSFRow row = st.getRow(rowIndex);
if (row == null) {
continue;
}
int tempRowSize = row.getLastCellNum() + 1;
if (tempRowSize > rowSize) {
rowSize = tempRowSize;
}
String[] values = new String[rowSize];
Arrays.fill(values, "");
boolean hasValue = false;
for (short columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) {
String value = "";
cell = row.getCell(columnIndex);
if (cell != null) {
// 注意:一定要设成这个,否则可能会出现乱码
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
value = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
if (date != null) {
value = new SimpleDateFormat("yyyy-MM-dd")
.format(date);
} else {
value = "";
}
} else {
value = new DecimalFormat("0").format(cell
.getNumericCellValue());
}
break;
case HSSFCell.CELL_TYPE_FORMULA:
// 导入时如果为公式生成的数据则无值
if (!cell.getStringCellValue().equals("")) {
value = cell.getStringCellValue();
} else {
value = cell.getNumericCellValue() + "";
}
break;
case HSSFCell.CELL_TYPE_BLANK:
break;
case HSSFCell.CELL_TYPE_ERROR:
value = "";
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
value = (cell.getBooleanCellValue() == true ? "Y"
: "N");
break;
default:
value = "";
}
}
if (columnIndex == 0 && value.trim().equals("")) {
break;
}
values[columnIndex] = rightTrim(value);
hasValue = true;
}
if (hasValue) {
result.add(values);
}
}
}
in.close();
String[][] returnArray = new String[result.size()][rowSize];
for (int i = 0; i < returnArray.length; i++) {
returnArray[i] = (String[]) result.get(i);
}
return returnArray;
}
/**
* 去掉字符串右边的空格
* @param str 要处理的字符串
* @return 处理后的字符串
*/
public static String rightTrim(String str) {
if (str == null) {
return "";
}
int length = str.length();
for (int i = length - 1; i >= 0; i--) {
if (str.charAt(i) != 0x20) {
break;
}
length--;
}
return str.substring(0, length);
}
}
File file = new File("c:\\a.xls");
InputStream in = new FileInputStream(file);
Workbook workbook = Workbook.getWorkbook(in);
//获取第一张Sheet表
Sheet sheet = workbook.getSheet(0);
//我们既可能通过Sheet的名称来访问它,也可以通过下标来访问它。如果通过下标来访问的话,要注意的一点是下标从0开始,就像数组一样。
//获取第一行,第一列的值
Cell c00 = rs.getCell(0, 0);
String strc00 = c00.getContents();
//获取第一行,第二列的值
Cell c10 = rs.getCell(1, 0);
String strc10 = c10.getContents();
//我们可以通过指定行和列得到指定的单元格Cell对象
Cell cell = sheet.getCell(column, row);
//也可以得到某一行或者某一列的所有单元格Cell对象
Cell[] cells = sheet.getColumn(column);
Cell[] cells2 = sheet.getRow(row);
//然后再取每一个Cell中的值
String content = cell.getContents();
用java读取excle文件用list,map接收,list实现了,map怎么也不行,急死了。
分享| 2013-06-30 21:19 匿名 | 浏览 177 次
public static void main(String[] args) throws Exception {
Workbook workbook=null;
Sheet sheet=null;
List list =new ArrayList();
InputStream input=new FileInputStream("E://tt.xls");
workbook =Workbook.getWorkbook(input);
sheet=workbook.getSheet(0);
for (int i = 0; i <sheet.getRows(); i++) {
String []str=new String[sheet.getColumns()];
for (int j = 0; j <sheet.getColumns(); j++) {
Cell cell=sheet.getCell(j,i);
str[j]=cell.getContents();
}
list.add(str);
}
for (int i = 0; i < list.size(); i++) {
String[]str=(String[]) list.get(i);
for (int j = 0; j < str.length; j++) {
System.out.println(str[j]);
}
}
}
这是list的方法,求一个map的跟遍历输出谢谢。
首先感谢,劳驾你再帮帮忙,map中key的值是标题,比如标题是姓名,年龄,住址。数据是张三,12,海南。
2013-06-30 22:00 提问者采纳
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;
import jxl.*;
public class Test3{
public static void main(String[] args) throws Exception {
Workbook workbook=null;
Sheet sheet=null;
TreeMap<Integer,String[]> map = new TreeMap<Integer,String[]>();
InputStream input=new FileInputStream("D://tt.xls");
workbook =Workbook.getWorkbook(input);
sheet=workbook.getSheet(0);
for (int i = 0; i <sheet.getRows(); i++) {
String []str=new String[sheet.getColumns()];
for (int j = 0; j <sheet.getColumns(); j++) {
Cell cell=sheet.getCell(j,i);
str[j]=cell.getContents();
}
map.put(i+1, str);
}
for (int i = 0; i < map.size(); i++) {
for (int j = 0; j < map.get(i+1).length; j++) {
System.out.print(map.get(i+1)[j]+" ");
}
System.out.println();
}
}
}
你是想要这种效果吗?
追问:
劳驾你再帮帮忙,map中key的值是标题,比如标题是姓名,年龄,住址。数据是张三,12,海南。
追答:
请问你的意思是 key里面存放列名 然后value里面存数据 然后 打印的时候 也要把 key值打出来吗?
public class Test3{
public static void main(String[] args) throws Exception {
Workbook workbook=null;
String columnName[] = {"姓名","年龄","住址"};
for(int i=0;i<columnName.length;i++){
System.err.print(columnName[i]+"\t");
}
System.out.println();
Sheet sheet=null;
TreeMap<String,String[]> map = new TreeMap<String,String[]>();
InputStream input=new FileInputStream("D://tt.xls");
workbook =Workbook.getWorkbook(input);
sheet=workbook.getSheet(0);
for (int i = 0; i <sheet.getColumns(); i++) {
String []str=new String[sheet.getRows()];
for (int j = 0; j <sheet.getRows(); j++) {
Cell cell=sheet.getCell(i,j);
str[j]=cell.getContents();
}
map.put(columnName[i], str);
}
for (int i = 0, j=0; i<map.get(columnName[j]).length; i++) {
for ( j = 0; j < map.size(); j++) {
System.out.print(map.get(columnName[j])[i]+"\t");
}
j=0;
System.out.println();
}
}
}
还可以用poi读取
http://www.cnblogs.com/hongten/p/java_poi_excel.html
这篇blog是介绍java中的poi技术读取Excel数据,然后保存到MySQL数据中。
你也可以在 : java的poi技术读取和导入Excel 了解到写入Excel的方法信息
使用JXL技术可以在 : java的jxl技术导入Excel
项目结构:
Excel中的测试数据:
数据库结构:
对应的SQL:
复制代码
1 CREATE TABLE student_info
(
2 id
int(11) NOT NULL AUTO_INCREMENT,
3 no
varchar(20) DEFAULT NULL,
4 name
varchar(20) DEFAULT NULL,
5 age
varchar(10) DEFAULT NULL,
6 score
float DEFAULT '0',
7 PRIMARY KEY (id
)
8 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
复制代码
插入数据成功:
如果重复数据,则丢掉:
源码部分:
/ExcelTest/src/com/b510/client/Client.java
复制代码
1 /**
2 *
3 /
4 package com.b510.client;
5
6 import java.io.IOException;
7 import java.sql.SQLException;
8
9 import com.b510.excel.SaveData2DB;
10
11 /*
12 * @author Hongten
13 * @created 2014-5-18
14 */
15 public class Client {
16
17 public static void main(String[] args) throws IOException, SQLException {
18 SaveData2DB saveData2DB = new SaveData2DB();
19 saveData2DB.save();
20 System.out.println("end");
21 }
22 }
复制代码
/ExcelTest/src/com/b510/common/Common.java
复制代码
1 /**
2 *
3 /
4 package com.b510.common;
5
6 /*
7 * @author Hongten
8 * @created 2014-5-18
9 */
10 public class Common {
11
12 // connect the database
13 public static final String DRIVER = "com.mysql.jdbc.Driver";
14 public static final String DB_NAME = "test";
15 public static final String USERNAME = "root";
16 public static final String PASSWORD = "root";
17 public static final String IP = "192.168.1.103";
18 public static final String PORT = "3306";
19 public static final String URL = "jdbc:mysql://" + IP + ":" + PORT + "/" + DB_NAME;
20
21 // common
22 public static final String EXCEL_PATH = "lib/student_info.xls";
23
24 // sql
25 public static final String INSERT_STUDENT_SQL = "insert into student_info(no, name, age, score) values(?, ?, ?, ?)";
26 public static final String UPDATE_STUDENT_SQL = "update student_info set no = ?, name = ?, age= ?, score = ? where id = ? ";
27 public static final String SELECT_STUDENT_ALL_SQL = "select id,no,name,age,score from student_info";
28 public static final String SELECT_STUDENT_SQL = "select * from student_info where name like ";
29 }
复制代码
/ExcelTest/src/com/b510/excel/ReadExcel.java
复制代码
1 /**
2 *
3 /
4 package com.b510.excel;
5
6 import java.io.FileInputStream;
7 import java.io.IOException;
8 import java.io.InputStream;
9 import java.util.ArrayList;
10 import java.util.List;
11
12 import org.apache.poi.hssf.usermodel.HSSFCell;
13 import org.apache.poi.hssf.usermodel.HSSFRow;
14 import org.apache.poi.hssf.usermodel.HSSFSheet;
15 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
16
17 import com.b510.common.Common;
18 import com.b510.excel.vo.Student;
19
20 /*
21 * @author Hongten
22 * @created 2014-5-18
23 */
24 public class ReadExcel {
25
26 public List readXls() throws IOException {
27 InputStream is = new FileInputStream(Common.EXCEL_PATH);
28 HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
29 Student student = null;
30 List list = new ArrayList();
31 // 循环工作表Sheet
32 for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
33 HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
34 if (hssfSheet == null) {
35 continue;
36 }
37 // 循环行Row
38 for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
39 HSSFRow hssfRow = hssfSheet.getRow(rowNum);
40 if (hssfRow != null) {
41 student = new Student();
42 HSSFCell no = hssfRow.getCell(0);
43 HSSFCell name = hssfRow.getCell(1);
44 HSSFCell age = hssfRow.getCell(2);
45 HSSFCell score = hssfRow.getCell(3);
46 student.setNo(getValue(no));
47 student.setName(getValue(name));
48 student.setAge(getValue(age));
49 student.setScore(Float.valueOf(getValue(score)));
50 list.add(student);
51 }
52 }
53 }
54 return list;
55 }
56
57 @SuppressWarnings("static-access")
58 private String getValue(HSSFCell hssfCell) {
59 if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
60 // 返回布尔类型的值
61 return String.valueOf(hssfCell.getBooleanCellValue());
62 } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
63 // 返回数值类型的值
64 return String.valueOf(hssfCell.getNumericCellValue());
65 } else {
66 // 返回字符串类型的值
67 return String.valueOf(hssfCell.getStringCellValue());
68 }
69 }
70 }
复制代码
/ExcelTest/src/com/b510/excel/SaveData2DB.java
复制代码
1 /**
2 *
3 /
4 package com.b510.excel;
5
6 import java.io.IOException;
7 import java.sql.SQLException;
8 import java.util.List;
9
10 import com.b510.common.Common;
11 import com.b510.excel.util.DbUtil;
12 import com.b510.excel.vo.Student;
13
14 /*
15 * @author Hongten
16 * @created 2014-5-18
17 */
18 public class SaveData2DB {
19
20 @SuppressWarnings({ "rawtypes" })
21 public void save() throws IOException, SQLException {
22 ReadExcel xlsMain = new ReadExcel();
23 Student student = null;
24 List list = xlsMain.readXls();
25
26 for (int i = 0; i < list.size(); i++) {
27 student = list.get(i);
28 List l = DbUtil.selectOne(Common.SELECT_STUDENT_SQL + "'%" + student.getName() + "%'", student);
29 if (!l.contains(1)) {
30 DbUtil.insert(Common.INSERT_STUDENT_SQL, student);
31 } else {
32 System.out.println("The Record was Exist : No. = " + student.getNo() + " , Name = " + student.getName() + ", Age = " + student.getAge() + ", and has been throw away!");
33 }
34 }
35 }
36 }
复制代码
/ExcelTest/src/com/b510/excel/util/DbUtil.java
复制代码
1 /**
2 *
3 /
4 package com.b510.excel.util;
5
6 import java.sql.Connection;
7 import java.sql.DriverManager;
8 import java.sql.PreparedStatement;
9 import java.sql.ResultSet;
10 import java.sql.SQLException;
11 import java.util.ArrayList;
12 import java.util.List;
13
14 import com.b510.common.Common;
15 import com.b510.excel.vo.Student;
16
17 /*
18 * @author Hongten
19 * @created 2014-5-18
20 /
21 public class DbUtil {
22
23 /*
24 * @param sql
25 */
26 public static void insert(String sql, Student student) throws SQLException {
27 Connection conn = null;
28 PreparedStatement ps = null;
29 try {
30 Class.forName(Common.DRIVER);
31 conn = DriverManager.getConnection(Common.URL, Common.USERNAME, Common.PASSWORD);
32 ps = conn.prepareStatement(sql);
33 ps.setString(1, student.getNo());
34 ps.setString(2, student.getName());
35 ps.setString(3, student.getAge());
36 ps.setString(4, String.valueOf(student.getScore()));
37 boolean flag = ps.execute();
38 if(!flag){
39 System.out.println("Save data : No. = " + student.getNo() + " , Name = " + student.getName() + ", Age = " + student.getAge() + " succeed!");
40 }
41 } catch (Exception e) {
42 e.printStackTrace();
43 } finally {
44 if (ps != null) {
45 ps.close();
46 }
47 if (conn != null) {
48 conn.close();
49 }
50 }
51 }
52
53 @SuppressWarnings({ "unchecked", "rawtypes" })
54 public static List selectOne(String sql, Student student) throws SQLException {
55 Connection conn = null;
56 PreparedStatement ps = null;
57 ResultSet rs = null;
58 List list = new ArrayList();
59 try {
60 Class.forName(Common.DRIVER);
61 conn = DriverManager.getConnection(Common.URL, Common.USERNAME, Common.PASSWORD);
62 ps = conn.prepareStatement(sql);
63 rs = ps.executeQuery();
64 while(rs.next()){
65 if(rs.getString("no").equals(student.getNo()) || rs.getString("name").equals(student.getName())|| rs.getString("age").equals(student.getAge())){
66 list.add(1);
67 }else{
68 list.add(0);
69 }
70 }
71 } catch (Exception e) {
72 e.printStackTrace();
73 } finally {
74 if (rs != null) {
75 rs.close();
76 }
77 if (ps != null) {
78 ps.close();
79 }
80 if (conn != null) {
81 conn.close();
82 }
83 }
84 return list;
85 }
86
87
88 public static ResultSet selectAll(String sql) throws SQLException {
89 Connection conn = null;
90 PreparedStatement ps = null;
91 ResultSet rs = null;
92 try {
93 Class.forName(Common.DRIVER);
94 conn = DriverManager.getConnection(Common.URL, Common.USERNAME, Common.PASSWORD);
95 ps = conn.prepareStatement(sql);
96 rs = ps.executeQuery();
97 } catch (Exception e) {
98 e.printStackTrace();
99 } finally {
100 if (rs != null) {
101 rs.close();
102 }
103 if (ps != null) {
104 ps.close();
105 }
106 if (conn != null) {
107 conn.close();
108 }
109 }
110 return rs;
111 }
112
113 }
复制代码
/ExcelTest/src/com/b510/excel/vo/Student.java
复制代码
1 /**
2 *
3 /
4 package com.b510.excel.vo;
5
6 /*
7 * Student
8 *
9 * @author Hongten
10 * @created 2014-5-18
11 /
12 public class Student {
13 /*
14 * id
15 /
16 private Integer id;
17 /*
18 * 学号
19 /
20 private String no;
21 /*
22 * 姓名
23 /
24 private String name;
25 /*
26 * 学院
27 /
28 private String age;
29 /*
30 * 成绩
31 */
32 private float score;
33
34 public Integer getId() {
35 return id;
36 }
37
38 public void setId(Integer id) {
39 this.id = id;
40 }
41
42 public String getNo() {
43 return no;
44 }
45
46 public void setNo(String no) {
47 this.no = no;
48 }
49
50 public String getName() {
51 return name;
52 }
53
54 public void setName(String name) {
55 this.name = name;
56 }
57
58 public String getAge() {
59 return age;
60 }
61
62 public void setAge(String age) {
63 this.age = age;
64 }
65
66 public float getScore() {
67 return score;
68 }
69
70 public void setScore(float score) {
71 this.score = score;
72 }
73
74 }
复制代码
源码下载:http://files.cnblogs.com/hongten/ExcelTest.zip