Actualmente, mais comumente utilizados para alcançar importação Java, exportar Excel, existem duas tecnologias Java e Jacarta POI do Excel
Diretamente no código:
Um, POI
POI é um projeto Apache, para ser Microsoft Word Excel, PPT operar, incluindo office2003 e 2007, Excl2003 e 2007. poi agora foi atualizado. Portanto, agora o uso dominante POI.
xls:
pom:
org.apache.poi
poi-OOXML
3,9
commons-io
commons-io
2.2
exportação:
classe pública PoiCreateExcel {
public static void main (String [] args) {
// cria o cabeçalho
String [] title = { "id", "nome", "sexo"};
// cria um livro do Excel
HSSFWorkbook pasta de trabalho = novo HSSFWorkbook ();
// cria uma folha de planilha
HSSFSheet folha workbook.createSheet = ();
// Criar a primeira linha
HSSFRow fileira = sheet.createRow (0);
célula HSSFCell = nulo;
// inserir a primeira linha
para (int i = 0; i <title.length; i ++) {
células = row.createCell (i);
cell.setCellValue (título [i]);
}
// acrescentar dados
para (int i = 1; i <10; i ++) {// int iniciar aqui é a segunda linha é um
HSSFRow nextrow = sheet.createRow (i);
HSSFCell cell2 = nexTrow.createCell (0);
cell2.setCellValue ( "um" + i);
cell2 = nexTrow.createCell (1);
cell2.setCellValue ( "utilizador");
cell2 = nexTrow.createCell (2);
cell2.setCellValue ( "男");
}
// cria um arquivo
arquivo file = new File ( "d: /poi.xls");
experimentar {
file.createNewFile ();
// salva conteúdo
fluxo FileOutputStream = FileUtils.openOutputStream (arquivo);
workbook.write (fluxo);
stream.close ();
} Catch (exceção e) {
e.printStackTrace ();
}
}
}
importação:
classe pública PoiReadExcel {
public static void main (String [] args) {
// introdução ao arquivo parse
arquivo file = new File ( "d: /poi.xls");
experimentar {
// Criar Excel lê o conteúdo do arquivo
HSSFWorkbook pasta de trabalho = new HSSFWorkbook (FileUtils.openInputStream (arquivo));
/ **
* A primeira página lê Sheet
* /
// HSSFSheet folha = workbook.getSheet ( "Sheet0");
/ **
* A segunda maneira de ler a página Sheet
* /
HSSFSheet folha workbook.getSheetAt = (0);
int firstRowNum = 0; // começar linha, linha 0
int lasrRowNum = sheet.getLastRowNum (); // ler até a última linha
para (int i = 0; i <lasrRowNum; i ++) {
HSSFRow fileira = sheet.getRow (i);
// Obter a última célula o número da coluna atual
int lastCellNum = row.getLastCellNum ();
para (int j = 0; j <lastCellNum; j ++) {
HSSFCell célula = row.getCell (j);
String value = cell.getStringCellValue (); // Nota Se Excel que valores são corda, em seguida, getStringCellValue se outro tipo que você precisa para mudar!
System.out.print (valor + " ");
}
System.out.printlnl ();
}
} Catch (exceção e) {
e.printStackTrace ();
}
}
}
xlsx:
pom:
org.apache.poi
poi-exemplos
3,9
org.apache.poi
em seguida,-excelant
3,9
org.apache.poi
poi-OOXML
3,9
org.apache.poi
esquemas poi-OOXML
3,9
org.apache.poi
em seguida,-bloco de rascunho
3,9
exportação:
classe pública PoiCreateExcel {
public static void main (String [] args) {
// cria o cabeçalho
String [] title = { "id", "nome", "sexo"};
// cria um livro do Excel
XSSFWorkbook pasta de trabalho = novo XSSFWorkbook ();
// Criar um shheet planilha
folha folha workbook.createSheet = ();
// Criar a primeira linha
linha fileira = sheet.createRow (0);
Cell = nulo;
// inserir a primeira linha
para (int i = 0; i <title.length; i ++) {
células = row.createCell (i);
cell.setCellValue (título [i]);
}
// acrescentar dados
para (int i = 1; i <10; i ++) {// int iniciar aqui é a segunda linha é um
Fila nextrow = sheet.createRow (i);
cell2 celular = nexTrow.createCell (0);
cell2.setCellValue ( "um" + i);
cell2 = nexTrow.createCell (1);
cell2.setCellValue ( "utilizador");
cell2 = nexTrow.createCell (2);
cell2.setCellValue ( "男");
}
// cria um arquivo
arquivo file = new File ( "d: /poi.xlsx"); // aqui pode ser modificado para versões superiores
experimentar {
file.createNewFile ();
// O conteúdo da bandeja atividades bônus forex
fluxo FileOutputStream = FileUtils.openOutputStream (arquivo);
workbook.write (fluxo);
stream.close ();
} Catch (exceção e) {
e.printStackTrace ();
}
}
}
importação:
classe pública PoiReadExcel {
Lista pública readExcels (InputStream é) throws Exception {
Lista xlsxList = new ArrayList ();
experimentar {
se (é == null) {
throw new IOException ( "arquivo está incorreta!");
}
Livro livro = WorkbookFactory.create (é);
FormulaEvaluator fe = workbook.getCreationHelper () createFormulaEvaluator ().;
// Obter a primeira tabela
folha folha workbook.getSheetAt = (0);
se (folha == null) {
throw new IOException ( "excel entrada na primeira tabela está vazia!");
}
para (int rowNum = 0; rowNum <= sheet.getLastRowNum (); rowNum ++) {
linha fileira = sheet.getRow (rowNum);
if (row! = null) {
// Obter a coluna inicial da linha atual
int firstCellNum = row.getFirstCellNum ();
// Obter o número de colunas na linha atual
int lastCellNum = row.getPhysicalNumberOfCells ();
resultado String = "";
// linha atual ciclo
para (int cellNum = firstCellNum; cellNum <lastCellNum; cellNum ++) {
Cell = row.getCell (cellNum);
duplo valor = 0;
Corda valueString = cell.getStringCellValue ();
se (null! = fe.evaluate (celular)) {
= valor fe.evaluate (célula) .getNumberValue ();
}
// result = result + cellNum + ":" + valor + "----";
result = result + cellNum + ":" + valueString + "----";
}
System.out.printlnl (resultado + " ");
}
}
is.close ();
} Catch (FileNotFoundException e) {
throw new Exception ( "Arquivo não é correto!");
}
voltar xlsxList;
}
public static void main (String [] args) throws Exception {
InputStream é = novo FilelnputStream ( "d: /poi.xlsx");
PoiReadExcel re PoiReadExcel = novo ();
re.readExcels (é);
}
}
二, JXL
JXL Excel só pode operar pertencem ao quadro mais velho, ele só suporta a versão do Excel 95-2000. Agora temos parado atualização e manutenção.
pom:
net.sourceforge.jexcelapi
jxl
2.6.10
exportação:
classe pública JxlCreateExcel {
public static void main (String [] args) {
// Primeiro, defina a cabeça mesa primeira linha do nome da tabela é o nome da coluna
String [] title = { "id", "nome", "sexo"};
// cria um arquivo do Excel para o caminho
arquivo file = new File ( "d: /jxl.xls");
experimentar {
file.createNewFile ();
// cria a pasta de trabalho
WritableWorkbook livro = Workbook.createWorkbook (arquivo);
// cria folha
WritableSheet folha = workbook.createSheet ( "sheet1", 0);
// dados add
Etiqueta label = nulo;
// A primeira linha define o nome da coluna
para (int i = 0; i <title.length; i ++) {
label = nova etiqueta (i, 0, título [i]);
sheet.addCell (etiqueta);
}
// anexa dados da segunda linha da i começando
para (int i = 1; i <9; i ++) {
label = new Label (0, i, "id:" + i);
sheet.addCell (etiqueta);
label = nova etiqueta (1, i, "utilizador");
sheet.addCell (etiqueta);
label = nova etiqueta (2, i, "男");
sheet.addCell (etiqueta);
}
// gravação e, finalmente, perto do córrego
workbook.write ();
workbook.close ();
} Catch (exceção e) {
e.printStackTrace ();
}
}
}
importação:
classe pública JxlReadExcel {
public static void main (String [] args) {
experimentar {
// cria livro
Pasta de trabalho pasta de trabalho = Workbook.getWorkbook (new File ( "d: /jxl.xls"));
// Obter a folha de planilha
folha folha workbook.getSheet = (0);
// Obter os dados
para (int i = 0; i <sheet.getRows (); i ++) {// 获取 行
para (int j = 0; j <sheet.getColumns (); j ++) {// Obter a coluna
Cell = sheet.getCell (j, i);
System.out.print (cell.getContents (+) ""); // obter o conteúdo da célula
}
System.out.printlnl ();
}
workbook.close ();
} Catch (exceção e) {
e.printStackTrace ();
}
}
}