1. 程式人生 > >java實現excel的匯入

java實現excel的匯入

package com.nchu.wechatOrder.controller;

 

import jxl.Cell;

import jxl.Sheet;

import jxl.Workbook;

import jxl.read.biff.BiffException;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

 

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.util.ArrayList;

import java.util.List;

 

@Controller

public class ExcelController {

 

private String filePath;

private List list = new ArrayList();

 

public ExcelController(String filePath) {

this.filePath = filePath;

}

 

private void readExcel() throws IOException, BiffException {

//建立輸入流

InputStream stream = new FileInputStream(filePath);

//獲取Excel檔案物件

Workbook rwb = Workbook.getWorkbook(stream);

//獲取檔案的指定工作表 預設的第一個

Sheet sheet = rwb.getSheet(0);

//行數(表頭的目錄不需要,從1開始)

for (int i = 0; i < sheet.getRows(); i++) {

//建立一個數組 用來儲存每一列的值

String[] str = new String[sheet.getColumns()];

Cell cell = null;

//列數

for (int j = 0; j < sheet.getColumns(); j++) {

//獲取第i行,第j列的值

cell = sheet.getCell(j, i);

str[j] = cell.getContents();

}

//把剛獲取的列存入list

list.add(str);

}

}

 

private void outData() {

for (int i = 0; i < list.size(); i++) {

String[] str = (String[]) list.get(i);

for (int j = 0; j < str.length; j++) {

System.out.print(str[j] + '\t');

}

System.out.println();

}

}

 

public static void main(String args[]) throws BiffException, IOException {

ExcelController excel = new ExcelController("/Users/user12/Desktop/student1.xls");

excel.readExcel();

excel.outData();

}

 

 

@RequestMapping("toExcel")

public String toExcel() {

return "admin/Excel";

}

 

 

//上傳excel

 

}