1、在项目开发过程中需要将Excel文件导入到数据库中,应用到jxl.jar 进行解析
2、如下
- package test;
- import java.io.File;
- import java.io.IOException;
- import java.io.UnsupportedEncodingException;
- import javax.servlet.http.HttpServletResponse;
- import jxl.Sheet;
- import jxl.Workbook;
- import jxl.WorkbookSettings;
- import jxl.read.biff.BiffException;
- import jxl.write.Label;
- import jxl.write.WritableSheet;
- import jxl.write.WritableWorkbook;
- import jxl.write.WriteException;
- public class JxlTest {
- public static void main(String[] args) {
- (new JxlTest()).excelRead();
- }
- public void excelRead(){
- File file = new File("d:\\cicc825.xls");
- try {
- WorkbookSettings workbookSettings=new WorkbookSettings();
- workbookSettings.setEncoding("ISO-8859-1"); //关键代码,解决中文乱码
- Workbook book= Workbook.getWorkbook(file,workbookSettings);
- //Workbook book= Workbook.getWorkbook(file);
- Sheet sheet=book.getSheet(0);
- int row = sheet.getRows();
- int column =sheet.getColumns();
- for(int i=0;i<row;i++){
- for(int j=0;j<column;j++){
- System.out.println(sheet.getCell(j, i).getContents());
- }
- }
- } catch (BiffException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public void excelWrite(HttpServletResponse response) {
- long time = System.currentTimeMillis();// 用当前的系统时间作为默认表名
- String name = String.valueOf(time);
- name ="position";
- String pathName = name + ".xls";
- try {
- pathName = new String(pathName.getBytes(), "ISO-8859-1");
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- // 获取弹出保存框的保存路径和表名
- response.setContentType("APPLICATION/OCTET-STREAM");
- response.setHeader("Content-Disposition", "attachment; filename=\"" + pathName + "\"");
- WritableWorkbook workbook;
- WorkbookSettings workbookSettings=new WorkbookSettings();
- workbookSettings.setEncoding("GB2312");
- try {
- workbook = Workbook.createWorkbook(response.getOutputStream(),workbookSettings);
- WritableSheet ws = workbook.createSheet("sheet 1", 0);
- ws.setColumnView(0,22);
- Label cell = null;
- for(int i=0;i<2;i++){
- cell = new Label(0, i+1, "id");
- ws.addCell(cell);
- cell = new Label(1, i+1, "name");
- ws.addCell(cell);
- }
- workbook.write();
- workbook.close(); // 一定要关闭, 否则没有保存Excel;
- } catch (IOException e) {
- e.printStackTrace();
- }catch (WriteException e) {
- e.printStackTrace();
- }
- }
- }
3、解析过程还是比较简单的。