java导出数据Excel总结
//创建获取到JFileChooser的文件名的JTextField
public JTextField
getTextField(Container c){
JTextField textField = null;
for (int i =
0; i < c.getComponentCount(); i++) {
Component cnt =
c.getComponent(i);
if (cnt instanceof JTextField) {
return
(JTextField) cnt;
}
if (cnt instanceof Container) {
textField
= getTextField((Container) cnt);
if (textField != null) {
return
textField;
}
}
}
return textField;
}
//导出结果
public String writeExcel(List<WxToken>
all,HttpServletResponse response){
try {
//
定义工作薄
//用户自定义选择文件夹
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
JFileChooser
chooser=new
JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
chooser.setMultiSelectionEnabled(false);
chooser.setAcceptAllFileFilterUsed(false);
chooser.setDialogTitle("保存数据文件");
//JFileChooser.showSaveDialog()设立默认文件名
JTextField
fileNameField =
getTextField(chooser);
fileNameField.setText(UUID.randomUUID().toString());
int result= chooser.showSaveDialog(null);
//设置取消
if (result !=
JFileChooser.APPROVE_OPTION)
{
System.out.println("你已取消并关闭了窗口!");
return "取消数据导出";
}
String path=chooser.getSelectedFile().getPath()+".xls";
//String path = "e:\\" + UUID.randomUUID().toString() +
;
WritableWorkbook book = Workbook.createWorkbook(new File(path));
// 定义工作表,参数0表示第一个工作表
WritableSheet sheet = book.createSheet("微信账号信息表",
0);
sheet.setColumnView(0,10);
sheet.setColumnView(1,20);
sheet.setColumnView(2,20);
sheet.setColumnView(3,20);
sheet.setColumnView(4,20);
sheet.setColumnView(5,20);
sheet.setColumnView(6,20);
sheet.setColumnView(7,20);
sheet.setColumnView(8,10);
// 3.定义单元格标题及其样式:
WritableCellFormat headFormat = new
WritableCellFormat(
new WritableFont(WritableFont.ARIAL, 12,
WritableFont.BOLD,
false,
UnderlineStyle.NO_UNDERLINE,
jxl.format.Colour.BLACK));
headFormat.setAlignment(Alignment.CENTRE);
// 居中对齐
headFormat.setVerticalAlignment(VerticalAlignment.CENTRE);//
居中对齐
headFormat.setBorder(Border.ALL,
BorderLineStyle.THIN);//设置边框线
headFormat.setBackground(jxl.format.Colour.GREEN);//设置背景颜色
//
单元格语法:Label("列索引","行索引","单元格内容","格式");
Label label0 = new Label(0, 0,
"账号类型",headFormat);
//
将单元格添加到工作表中
sheet.addCell(label0);
// 填充数据:
int i = 1;
//定义内容样式
WritableCellFormat contentFormat
= new
WritableCellFormat();
contentFormat.setAlignment(Alignment.CENTRE);
contentFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
for (WxToken wt : all) {
//账号类型
Label type=null;
if (wt.getType()==0) {
type =
new Label(0,i,"服务号");//按字符串方式处理(会在单元格上生成绿色标记)
}
if (wt.getType()==1)
{
type = new
Label(0,i,"订阅号");//按字符串方式处理(会在单元格上生成绿色标记)
}
//
添加备注
WritableCellFeatures wcf = new
WritableCellFeatures();//备注
wcf.setComment("备注:"+wt.getRemark());
wxName.setCellFeatures(wcf);
sheet.addCell(type);
i++;
}
book.write();
book.close();
return
"数据导出成功";
}catch (Exception e) {
e.printStackTrace();
return
"数据导出失败";
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。