jsp中excel文件的創建與讀取


1.創建excel文件
//這里的jxl不是java的標准jar包,需要在項目中另外加載 import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; public class ExcelDownload extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 生成xls try { Date d = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_kkmmss "); String random = sdf.format(d); String targetFile = random + ".excel"; response.setContentType("application/vnd.ms-excel"); response.addHeader("Content-Disposition", "attachment; filename=\"" + targetFile + "\""); OutputStream os = response.getOutputStream(); WritableWorkbook wwb = Workbook.createWorkbook(os); // 新建一張表 WritableSheet wsheet = wwb.createSheet("record", 0); // 設置表頭 Label label = new Label(0, 0, ""); wsheet.addCell(label); label = new Label(0, 0, "會員姓名"); wsheet.addCell(label); label = new Label(1, 0, "卡號"); wsheet.addCell(label); label = new Label(2, 0, "聯系地址"); wsheet.addCell(label); label = new Label(3, 0, "郵編"); wsheet.addCell(label); label = new Label(4, 0, "聯系電話"); wsheet.addCell(label); label = new Label(5, 0, "手機"); wsheet.addCell(label); label = new Label(6, 0, "Email"); wsheet.addCell(label); label = new Label(7, 0, "性別"); wsheet.addCell(label); wwb.write(); wwb.close(); os.close(); response.flushBuffer(); } catch (Exception e) { System.out.println("生成信息表(Excel格式)時出錯:"); e.printStackTrace(); } } }

2.讀取excel文件

import java.io.*;
import jxl.*;
public class ReadExcel 
{
public static void main(String[] args) 
{
try{
Workbook book=Workbook.getWorkbook(new File("c:\test.xls")); 
//獲得第一個工作表對象
Sheet sheet=book.getSheet(0);
//得到第2行第1列的單元格
Cell cell1=sheet.getCell(0,1);
String result=cell1.getContents();
System.out.println(result);
book.close();
}
catch(Exception e){
System.out.println(e);
}
}
}

3.修改excel文件,執行結果是在原有文件中加入了一個新的工作表

import java.io.*;
import jxl.*;
import jxl.write.*;
public class UpdateExcel 
{
 
 public static void main(String[] args) 
{
  try  {
   //獲得Excel文件
   Workbook wb=Workbook.getWorkbook(new File("c://test.xls"));  
   //打開一個文件的副本,並且指定數據寫回到原文件
   WritableWorkbook book=
   Workbook.createWorkbook(new File("c://test.xls"),wb);  
   //添加一個工作表eet,在第一行第一列填寫內容
   WritableSheet sheet=book.createSheet("第二頁",1);
   sheet.addCell(new Label(0,0,"http://www.sunleap.com"));  
   book.write();
   book.close();
  }catch(Exception e){
   System.out.println(e);
  }
  System.out.println("操作結束!");
  
 }
}

詳細使用,請參考jxl的api文檔

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM