以前有一些简单的例子,由于项目中的数字为16位,一般的导出到EXCEL不能自动设为文本格式,现在这个可以解决些问题:
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
import jxl.Workbook;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.ihd.po.CardsInfoPO;
import com.ihd.po.ProvincesPO;
import com.ihd.service.InterService;
import com.ihd.util.PoiDemo;
public class CreateExcelService implements InterService {
@Override
public String doService(HttpServletRequest request,
HttpServletResponse response) {
List<CardsInfoPO> cardlist = (List<CardsInfoPO>)request.getSession().getAttribute("cardlist");
if(cardlist == null){
JOptionPane.showMessageDialog(null, "没有任何数据要导出,请检查!");
return "bgjsp/searchCardsInput.do";
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss" );
String date = sdf.format(new Date());
String targetfile = "C:/"+date+".xls";// 输出的excel文件名
String[] title = { "地区", "批次", "卡号","密码" };// excel工作表的标题
WritableWorkbook workbook;
try {
// 创建可写入的Excel工作薄,运行生成的文件在tomcat/bin下
// workbook = Workbook.createWorkbook(new File("output.xls"));
//System.out.println("begin");
OutputStream os = new FileOutputStream(targetfile);
workbook = Workbook.createWorkbook(os);
for(int j=0; j<4; j++) {
String worksheet = "List"+(j+1);// 输出的excel文件工作表名
WritableSheet sheet = workbook.createSheet(worksheet, j); // 添加第一个工作表
jxl.write.Label label;
jxl.write.Label label1;
jxl.write.Label label2;
jxl.write.Label label3;
for (int i = 0; i < title.length; i++) {
// Label(列号,行号 ,内容 )
label = new jxl.write.Label(i, 0, title[i]); // put the title
// in row1
sheet.addCell(label);
}
for(int i=0;i<cardlist.size();i++){
label1 = new jxl.write.Label(0, i+1,cardlist.get(i).getProvinces().getProvincesName() );
label2 = new jxl.write.Label(1, i+1, cardlist.get(i).getBatch());
label = new jxl.write.Label(2, i+1, cardlist.get(i).getCardID());
label3 = new jxl.write.Label(3, i+1, cardlist.get(i).getCardPwd());
sheet.addCell(label1);
sheet.addCell(label2);
sheet.addCell(label);
sheet.addCell(label3);
}
}
workbook.write();
workbook.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "表格导出出错,错误信息 :"+e+"\n错误原因可能是表格已经打开。");
e.printStackTrace();
}
JOptionPane.showMessageDialog(null, "表格已成功导出到"+targetfile);
return "bgjsp/searchCardsInput.do";
}
}