首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

JAVA操作excel的一些事例

2012-12-20 
JAVA操作excel的一些例子JAVA操作EXCEL有两种办法,一个用POI,一个用JXI,好象听说JXI对中文的支持会稍微好

JAVA操作excel的一些例子

JAVA操作EXCEL有两种办法,一个用POI,一个用JXI,好象听说JXI对中文的支持会稍微好些.

1 用POI,一个写的例子:
??

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.*;
import java.io.*;

public class Write {

?/**
? * @param args
? */
?public static void main(String[] args) {
??try
??{
??// TODO Auto-generated method stub
HSSFWorkbook wb=new HSSFWorkbook();
?? HSSFSheet sheet=wb.createSheet("new sheet");
?? HSSFRow row=sheet.createRow((short)1);??
?? row.createCell((short)1).setCellValue(1.2);??
?? row.createCell((short)2).setCellValue("hellow way");?
?? row.createCell((short)3).setCellValue("aaaaa");????
?? FileOutputStream fileout=new FileOutputStream("c:\\aa.xls");?
????? wb.write(fileout);?????????????????????????
????? fileout.close();
?????
????? System.out.println("aaa");
??}
??catch(Exception e)
??{}
?}

2 读的例子:
?? CustomerDAO customerDAO = new CustomerDAO();
???String accounts = (String) request.getSession()
?????.getValue("accounts");

???String fileToBeRead = request.getRealPath("/")
?????+ "customer\\excel\\upload_" + accounts + ".xls";
???try {
????HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(
??????fileToBeRead));
????HSSFSheet sheet = workbook.getSheetAt(0);
????/* 读取文件中的信息,并把数据存入数据库 */
????for (int j = 1;; j++) {
?????HSSFRow row = sheet.getRow(j);
?????if (row != null) {
??????CustomerDTO customerDTO = new CustomerDTO();
??????HSSFCell cell;
??????int i = 0;
??????/* 跳过第一列的customerInformationID */
??????i++;
??????cell = row.getCell((short) i++);
??????customerDTO.setCompanyName(cell.getStringCellValue());
??????cell = row.getCell((short) i++);
??????customerDTO.setCustomerName(cell.getStringCellValue());
??????cell = row.getCell((short) i++);
??????customerDTO.setNameForShort(cell.getStringCellValue());
??????cell = row.getCell((short) i++);
??????customerDTO
????????.setCompanyAddress(cell.getStringCellValue());
??????cell = row.getCell((short) i++);
??????customerDTO.setCountry(cell.getStringCellValue());
??????cell = row.getCell((short) i++);
??????customerDTO.setProvince(cell.getStringCellValue());
??????cell = row.getCell((short) i++);
??????customerDTO.setCity(cell.getStringCellValue());
??????cell = row.getCell((short) i++);
??????customerDTO.setPostalcode(cell.getStringCellValue());
??????cell = row.getCell((short) i++);
??????customerDTO.setCompanyHomePage(cell
????????.getStringCellValue());
??????
??????customerDAO.insertCustomer(customerDTO);
?????} else {
??????break;
?????}
????}
???} catch (Exception e) {
????e.printStackTrace();
???}

热点排行