1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
1 .创建excel文件<br> //这里的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文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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文件,执行结果是在原有文件中加入了一个新的工作表
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
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文档
本文转自二郎三郎博客园博客,原文链接:http://www.cnblogs.com/haore147/p/3617973.html,如需转载请自行联系原作者