JAVA程序将数据导出excel资料
一、利用JXL导出
JAR包和项目地址:http://jexcelapi.sourceforge.net/
二、利用POI导出
JAR包和项目地址:http://poi.apache.org/
三、简单的例子
package excel.wanrue.shu.edu.cn;
import java.io.*;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import jxl.*;
import jxl.write.*;
import jxl.write.Number;
public class ExportExcel {
public static void main(String[] args) throws Exception {
ExportExcel.POI();
//
ExportExcel.JXL();
}
public static void JXL() throws Exception {
// 准备设置excel工作表的标题
String[] title = { "编号", "姓名", "成绩" };
// 输出的excel的路径
String filePath = "D:\\test.xls";
// 创建Excel工作薄
WritableWorkbook wwb;
// 新建立一个jxl文件,即在D盘下生成test.xls
OutputStream os = new FileOutputStream(filePath);
wwb = Workbook.createWorkbook(os);
// 添加第一个工作表并设置第一个Sheet的名字
WritableSheet sheet = wwb.createSheet("期末考试", 0);
Label label;
for (int i = 0; i < title.length; i++) {
// Label(x,y,z)其中x代表单元格的第x+1列,第y+1行, 单元格的内容是y
// 在Label对象的子对象中指明单元格的位置和内容
label = new Label(i, 0, title[i]);
// 将定义好的单元格添加到工作表中
sheet.addCell(label);
}
// 填充数据
// 填充编号
Number number = new Number(0, 1, 10720901);
sheet.addCell(number);
// 填充姓名
label = new Label(1, 1, "珑儿");
sheet.addCell(label);
// 填充姓名
number = new Number(2, 1, 92);
sheet.addCell(number);
// 写入数据
wwb.write();
// 关闭文件
wwb.close();
}
public static void POI() throws Exception {
// 创建一个EXCEL
HSSFWorkbook wb = new HSSFWorkbook();
// 创建一个SHEET
HSSFSheet sheet1 = wb.createSheet("期末考试");
String[] title = { "编号", "姓名", "成绩" };
int i = 0;
// 创建一行
HSSFRow row = sheet1.createRow((short) 0);
// 填充标题
for (String s : title) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(s);
i++;
}
HSSFRow row1 = sheet1.createRow((short) 1);
// 下面是填充数据
row1.createCell(0).setCellValue(10720902);
row1.createCell(1).setCellValue("怜影");
row1.createCell(2).setCellValue(99);
FileOutputStream fileOut = new FileOutputStream("d:\\test2.xls");
wb.write(fileOut);
fileOut.close();
}
}