java导出excel

代码示例:

package com.is.excel;

import java.io.File;
import java.io.FileOutputStream;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

/*
 * write data into a sheet of a excel
 */
public class ExportData {

	public static boolean exportExcel(String strFileName, String strSheetName,
			String strContent) {
		WritableWorkbook wwb;
		FileOutputStream fos;
		try{
			File f = new File(strFileName);
			// if file not exist, create xls; else modify xls
			if(f.exists() && f.length() > 0){
				Workbook wb = Workbook.getWorkbook(f);
				wwb = Workbook.createWorkbook(f, wb);
			} else{
				fos = new FileOutputStream(strFileName);
				wwb = Workbook.createWorkbook(fos);
			}
			WritableSheet ws = wwb.getSheet(strSheetName);
			// if sheet not exist, create sheet; else modify xls
			if(ws == null){
				ws = wwb.createSheet(strSheetName,wwb.getSheets().length);
			} else{
				ws.removeColumn(0);
				for(int i=0; i<ws.getColumns(); i++){
					ws.removeColumn(0);
				}
			}
			WritableFont wf = new WritableFont(WritableFont.createFont("微软雅黑"), 10,
					WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,
					Colour.BLACK);
			WritableCellFormat wcf = new WritableCellFormat(wf);
			wcf.setVerticalAlignment(VerticalAlignment.CENTRE);
			wcf.setAlignment(Alignment.CENTRE);
			wcf.setWrap(true);
			// set first row height
			ws.setRowView(0, 500);

			String[] strAccountManage = strContent.split("\r\n");
			String[] strField;
			int i=0,j=0;
			for(i=0; i<strAccountManage.length; i++){
				strField = strAccountManage[i].split(",");
				for(j=0; j<strField.length; j++){
					strField[j] = strField[j].replaceAll("\"", "");
					ws.addCell(new Label(j,i,strField[j],wcf));
				}
			}
			for(i=0; i<j; i++){
				// set column width
				ws.setColumnView(i, 20);
			}
			wwb.write();
			wwb.close();
			return true;
		} catch(Exception ex){
			ex.printStackTrace();
			return false;
		}
	}
}
注:涉及到文件的操作,建议慎重检查下代码安全性,尤其对于操作历史数据文件的情况。本人在应用上述代码的过程中就因为一个bug(sheet页不存在,未处理,导致文件写入失败),整个excel全被清空了,我积累了N久的历史数据就随之消失了(好在事发半月前拷贝了一个副本,不然。。。)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值