import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.*;
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class read implements ActionListener
{
JFrame frame;
JLabel label1,label2;
JTextField tf1,tf2;
JButton bu;
JPanel panel;
public read()
{
frame=new JFrame("aaaa");
panel=new JPanel();
label1=new JLabel("姓名:");
tf1=new JTextField(10);
label2=new JLabel("年龄:");
tf2=new JTextField(10);
bu=new JButton("导入");
panel.add(label1);
panel.add(tf1);
panel.add(label2);
panel.add(tf2);
panel.add(bu);
frame.getContentPane().add(panel);
bu.addActionListener(this);
frame.setSize(400,400);
frame.show();
}
/**
* @param args
*/
public static void main(String args[])
{
new read();
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource()==bu)
{
try
{
// TODO Auto-generated method stub
FileInputStream filein=new FileInputStream("bbc.xls"); 得到bbc.xls的输入流,
POIFSFileSystem fs=new POIFSFileSystem(filein); 从bbc.xls读
HSSFWorkbook wb=new HSSFWorkbook(fs); 工作薄
// POIFSFileSystem fs=new POIFSFileSystem(new FileInputStream("c:\\aa.xls"));
HSSFSheet sheet=wb.getSheetAt(0); 里面的工作表,第1个工作表
for (int i=0;i<7;i++)
{
HSSFRow row=sheet.getRow(i); 这里是读第1行,,这里做个循环读七行。。后面跟据这个row读列
System.out.println("i="+i);
if (row==null)continue; 这里最好加row==null continue 因为如果他读到null不加就会报错后面。。
for (int j=1;j<7;j++) 读七列
{
if (row.getCell((short)j)==null) 读到null continue跳 出
{
System.out.println("j="+j);
continue;
}
else if(row.getCell((short)j).getStringCellValue().trim().equals("name:")) 这里就是读到名字,就取他后面的值
{
int n=j+1;
System.out.println("name="+row.getCell((short)n).getStringCellValue().trim()); n就是列,
tf1.setText(row.getCell((short)n).getStringCellValue().trim()); 把它设置到TextField里面去
}
else if(row.getCell((short)j).getStringCellValue().trim().equals("age:")) 同上,但这里注意读数字要getNumericCellValue()
{ 要不就会报异常
int n=j+1;
System.out.println("age="+row.getCell((short)n).getNumericCellValue());
tf2.setText(String.valueOf(row.getCell((short)n).getNumericCellValue()));
}
else
{
System.out.println(row.getCell((short)j).getStringCellValue().trim());
}
}
}
filein.close();
System.out.println("aaa");
}
catch(Exception ex)
{
System.out.println("error "+ex.toString());
}
}
}
}
Java输出内容到Excel
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();
//POIFSFileSystem fs=new POIFSFileSystem(new FileInputStream("c:\\aa.xls"));
HSSFSheet sheet=wb.createSheet("new sheet"); 创建工作表名字为new sheet
HSSFRow row=sheet.createRow((short)1); 在第二行创建一行
row.createCell((short)1).setCellValue(1.2); 第二列写入1.2
row.createCell((short)2).setCellValue("hellow way"); 第三列写入hellow way
row.createCell((short)3).setCellValue("aaaaa"); 一样
FileOutputStream fileout=new FileOutputStream("aa.xls");
wb.write(fileout); 写出
fileout.close();
System.out.println("aaa");
}
catch(Exception e)
{}
}
}