java匯入匯出excel表格
阿新 • • 發佈:2019-02-12
這裡是通過jxl實現對excel的匯入匯出的,可以動態建立本地excel,讀取本地excel,寫入excel。
只需匯入jxl.jar包即可;
基本操作:
一:建立本地excel:
//建立EXECEL,新增資料,通過輸出流輸出到客戶端下載 public static void createExecel(HttpServletRequest request,HttpServletResponse response,String fileName){ OutputStream os=null; try { os=response.getOutputStream(); response.reset(); response.setCharacterEncoding("utf-8"); response.setHeader("Content-Disposition", "attachment;filename="+fileName); response.setContentType("application/msexcel"); //建立工作薄 WritableWorkbook wwb=Workbook.createWorkbook(os); //建立新的一頁 WritableSheet sheet=wwb.createSheet("First sheet", 0); //建立要顯示的內容,第一個引數為列,第二個引數為行,第三個引數為內容 Label xuexiao=new Label(0,0,"學校"); sheet.addCell(xuexiao); Label zhuanye=new Label(1,0,"專業"); sheet.addCell(zhuanye); Label xuexiao1=new Label(0,1,"清華大學"); sheet.addCell(xuexiao1); Label zhuanye1=new Label(1,1,"軟體工程"); sheet.addCell(zhuanye1); //把建立的內容寫入輸出流,並關閉 wwb.write(); wwb.close(); os.close(); } catch (Exception e) { e.printStackTrace(); } }
二:建立帶有 樣式的EXECEL
//建立帶有 樣式的EXECEL,新增資料,通過輸出流輸出到客戶端下載 public static void createStyleExecel(HttpServletRequest request,HttpServletResponse response,String fileName){ OutputStream os=null; try { os=response.getOutputStream(); response.reset(); response.setCharacterEncoding("utf-8"); response.setHeader("Content-Disposition", "attachment;filename="+fileName); response.setContentType("application/msexcel"); //建立工作薄 WritableWorkbook wwb=Workbook.createWorkbook(os); //建立新的一頁 WritableSheet sheet=wwb.createSheet("First sheet", 0); //構造表頭,合併單元格,第一個引數是起始列,第二個引數是起始行,第三個引數是終止列,第四個引數是終止行 sheet.mergeCells(0, 0, 1, 0); //設定字型為Arial,字號為10,黑體顯示 WritableFont wf=new WritableFont(WritableFont.ARIAL,10,WritableFont.BOLD); //生成一個單元格樣式控制物件 WritableCellFormat wcf=new WritableCellFormat(wf); //單元格的內容水平方向上居中 wcf.setAlignment(jxl.format.Alignment.CENTRE); //單元格的內容垂直方向上居中 wcf.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); //建立要顯示的內容,第一個引數為列,第二個引數為行,第三個引數為內容 Label title=new Label(0,0,"學校專業資訊表",wcf); //設定第一行的高度 sheet.setRowView(0,600,false); sheet.addCell(title); WritableFont wf1=new WritableFont(WritableFont.ARIAL); wf1.setColour(Colour.GOLD);//設定字型顏色 WritableCellFormat wcf1=new WritableCellFormat(wf1); Label fd=new Label(0,1,"學校",wcf1); sheet.addCell(fd); Label be=new Label(1,1,"專業",wcf1); sheet.addCell(be); Label rq=new Label(0,2,"清華大學"); sheet.addCell(rq); Label rq1=new Label(1,2,"軟體工程"); sheet.addCell(rq1); //把建立的內容寫入輸出流,並關閉 wwb.write(); wwb.close(); os.close(); } catch (Exception e) { e.printStackTrace(); } }
三:建立excel,從資料庫讀取資料寫入excel
//建立EXECEL,從資料庫匯入資料,輸出到客戶端下載 public static void createExecelData(HttpServletRequest request,HttpServletResponse response,StudentService studentService,String fileName){ OutputStream os=null; try { os=response.getOutputStream(); response.reset(); response.setCharacterEncoding("utf-8"); response.setHeader("Content-Disposition", "attachment;filename="+fileName); response.setContentType("application/msexcel"); //建立工作薄 WritableWorkbook wwb=Workbook.createWorkbook(os); //建立新的一頁 WritableSheet sheet=wwb.createSheet("First sheet", 0); //建立要顯示的內容,第一個引數為列,第二個引數為行,第三個引數為內容 Label studentId=new Label(0,0,"ID"); sheet.addCell(studentId); Label studentName=new Label(1,0,"姓名"); sheet.addCell(studentName); List<Student> students=studentService.findByHq("from Student s", null); for(int i=0;i<students.size();i++){ studentId=new Label(0,i+1,students.get(i).getStudentId()+""); studentName=new Label(1,i+1,students.get(i).getStudentName()); sheet.addCell(studentId); sheet.addCell(studentName); } //把建立的內容寫入輸出流,並關閉 wwb.write(); wwb.close(); os.close(); } catch (Exception e) { e.printStackTrace(); } }
四:讀取本地EXECEL檔案資料
//讀取本地EXECEL檔案資料
public static void readExcel(StudentService studentService,String filePath){
//建立只讀Workbook物件
Workbook wb=null;
try {
InputStream is=new FileInputStream(filePath);
wb=Workbook.getWorkbook(is);
//建立sheet表,sheet下標從0開始
Sheet sheet=wb.getSheet(0);
//獲取sheet表的總列數
int cols=sheet.getColumns();
System.out.println("列數:"+cols);
//獲取sheet表的總行數
int rows=sheet.getRows();
System.out.println("行數:"+rows);
//遍歷每個單元格
List<Student> students=new ArrayList<Student>();
for(int i=1;i<rows;i++){
Student s=new Student();
for(int j=0;j<cols;j++){
Cell cell=sheet.getCell(j,i);
System.out.println((i+","+j+":")+cell.getContents());
if(j==0){
s.setStudentId(Integer.valueOf(cell.getContents()));
}else{
s.setStudentName(cell.getContents());
}
}
students.add(s);
}
studentService.saveBatch(students);
System.out.println("batch ok");
} catch (Exception e) {
e.printStackTrace();
}
}
五 :實現通過jsp匯入資料,到資料庫:
分兩步實現,先把檔案上傳到伺服器本地,再讀取本地excel檔案
<form action="impExcel" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="匯入">
</form>
public String executeImport(){
HttpServletRequest request=ServletActionContext.getRequest();
HttpServletResponse response=ServletActionContext.getResponse();
//首先將檔案上傳至伺服器 f:\\temp目錄
InputStream is=null;
OutputStream os=null;
try {
System.out.println("in upload");
is=new FileInputStream(file);
path="F:\\temp\\"+fileFileName;
os=new FileOutputStream(new File(path));
byte[] b=new byte[1024];
int num;
while((num=is.read(b))!=-1){
os.write(b, 0, num);
os.flush();
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
os.close();
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//從伺服器讀取Execel
ExcelUtil.readExcel(studentService,"F:\\temp\\"+fileFileName);
System.out.println("匯入 execel ok");
return "all";
}
六 匯出excel
<a href="expExcel">匯出</a>
public String executeExport(){
HttpServletRequest request=ServletActionContext.getRequest();
HttpServletResponse response=ServletActionContext.getResponse();
// ExcelUtil.createExecel(request, response,fileName);
ExcelUtil.createExecelData(request, response,studentService,fileName);
// ExcelUtil.createStyleExecel(request, response,fileName);
System.out.println("匯出 execel ok");
return null;
}