第一步:ApachePoi的jar包导全,不全会出现异常。

第二步:写就完事了:此例为读取特定模板的excel,仅供参考,根据实际需求改写。

package 自建包;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
import javax.swing.filechooser.FileFilter;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 
public class FileChooserUtils2 implements ActionListener {
//初始面板
 private JFrame f = null;
 private JLabel label = null;
 private JTextArea textarea = null;
 private JFileChooser fileChooser = null;
 public FileChooserUtils2() {
  f = new JFrame("FileChooser Example");
  Container contentPane = f.getContentPane();
  textarea = new JTextArea();
  JScrollPane scrollPane = new JScrollPane(textarea);
  scrollPane.setPreferredSize(new Dimension(350, 300));
  JPanel panel = new JPanel();
  JButton b1 = new JButton("新建文件");
  b1.addActionListener(this);
  JButton b2 = new JButton("存储文件");
  b2.addActionListener(this);
  panel.add(b1);
  panel.add(b2);
  label = new JLabel(" ", JLabel.CENTER);
  fileChooser = new JFileChooser("C:\\Users\\xjung\\Desktop"); //默认是我的桌面,修改一下。
  contentPane.add(label, BorderLayout.NORTH);
  contentPane.add(scrollPane, BorderLayout.CENTER);
  contentPane.add(panel, BorderLayout.SOUTH);
  f.pack();
  f.setVisible(true);
  f.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);//按x不会退出程序
 }
 
 public static void main(String[] args) {
  new FileChooserUtils2();
 }
 
 public void actionPerformed(ActionEvent e) {
  File file = null;
  int result;
  if (e.getActionCommand().equals("新建文件")) {
   fileChooser.setApproveButtonText("确定");
   fileChooser.setDialogTitle("打开文件");
   fileChooser.addChoosableFileFilter(new JAVAFileFilter("xls", "xlsx"));   //加载过滤器
   fileChooser.addChoosableFileFilter(new JAVAFileFilter("java"));
   result = fileChooser.showOpenDialog(f);
   textarea.setText("");
   if (result == JFileChooser.APPROVE_OPTION) {
    file = fileChooser.getSelectedFile();
    label.setText("您选择打开的文件名称为:" + file.getName());
   } else if (result == JFileChooser.CANCEL_OPTION) {
    label.setText("您没有选择任何文件");
   }
   String extension="";
   int index = file.toString().lastIndexOf('.');
   if (index > 0 && index < file.toString().length() - 1) {
    extension = file.toString().substring(index + 1).toLowerCase();
   }
   if("xls".equals(extension)||"xlsx".equals(extension)) {
    readExcel(file.toString());
   }else {
    readNoExcel(file.toString());
   }
  }
  if (e.getActionCommand().equals("存储文件")) {
   result = fileChooser.showSaveDialog(f);
   file = null;
   if (result == JFileChooser.APPROVE_OPTION) {
    file = fileChooser.getSelectedFile();
    label.setText("您选择存储的文件名称为:" + file.getName());
   } else if (result == JFileChooser.CANCEL_OPTION) {
    label.setText("您没有选择任何文件");
   }
   FileOutputStream fileOutStream = null;
   if (file != null) {
    try {
     fileOutStream = new FileOutputStream(file);
    } catch (FileNotFoundException e2) {
     label.setText("File Not Found");
     return;
    }
    String content = textarea.getText();
    try {
     fileOutStream.write(content.getBytes());
    } catch (IOException e2) {
     label.setText("写入文件错误");
    } finally {
     try {
      if (fileOutStream != null)
       fileOutStream.close();
     } catch (IOException e3) {
     }
    }
   }
  }
 }
 
//读取非excel的文本方法
 private void readNoExcel(String file) {
  FileInputStream fileInStream = null;
  InputStreamReader isr = null;
  BufferedReader reader = null;
  if (file != null) {
   try {
    fileInStream = new FileInputStream(file);
    isr = new InputStreamReader(fileInStream, "UTF-8");
    reader = new BufferedReader(isr);
   } catch (FileNotFoundException e2) {
    label.setText("File Not Found");
    return;
   } catch (UnsupportedEncodingException e3) {
    label.setText("File Not Found");
    return;
   }
   String readStr;
   try {
    while ((readStr = reader.readLine()) != null) {
     textarea.append(readStr + "\n");
    }
   } catch (IOException e2) {
    label.setText("写入文件错误");
   } finally {
    try {
     if (fileInStream != null)
      fileInStream.close();
    } catch (IOException e3) {
    }
   }
  }
 }
 
//读取excel的内容
  private void readExcel(String fileName) {
         Workbook workbook = null;
         Row row = null;
       //获取Excel文档
         workbook = getWorkbook(fileName);
       //获取Excel文档的第一个sheet页
         Sheet sheet = workbook.getSheetAt(0);
       //获取文档中已保存数据的行数
         int rowNum = sheet.getPhysicalNumberOfRows();
       //获取第三行
         row = sheet.getRow(2);                                 //实现的是读取特定模板的excel,根据需求修改。
         int colnum=5;
         for (int i = 2; i < rowNum; i++) {
             row = sheet.getRow(i);
             if (null != row)
             {
              //获取当前行已保存数据的最大列数
              colnum = row.getPhysicalNumberOfCells();
                 for (int j = 0; j < colnum; j++) {
                     Cell cell =  row.getCell(j);
                     textarea.append(getValueFromCell(cell)+" ");
                     if(j==colnum-1) {
                      textarea.append("\n");
                     }
                 }
             }
         }
     }
 
     private static Workbook getWorkbook(String fileName) {//根据后缀获取Excel表格
         Workbook workbook = null;
         String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
         InputStream in = null;
         try {
             in = new FileInputStream(fileName);
             if ("xls".equals(suffix))
             {
                 workbook = new HSSFWorkbook(in);
             }
             else if ("xlsx".equals(suffix))
             {
                 workbook = new XSSFWorkbook(in);
             }
         } catch (FileNotFoundException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
         }
         return workbook;
     }
    
     private static String getValueFromCell(Cell cell) {//获取单元格的值ֵ
         String value = null;
         if (null == cell)
         {
             return "";
         }
       //判断cell类型
         switch(cell.getCellType()){
         case NUMERIC:{
             value = ""+(int)cell.getNumericCellValue();
             break;
         }
        
         case STRING:{
             value = cell.getStringCellValue();
             break;
         }
         default:
             value = "";
         }
         return value;
     }
}
//文件过滤器
class JAVAFileFilter extends FileFilter {
 String ext;
 String ext2;
 public JAVAFileFilter(String ext) {
  this.ext = ext;
 }
 public JAVAFileFilter(String ext, String ext2) {
  this.ext = ext;
  this.ext2 = ext2;
 }
//返回true过滤出文件
 public boolean accept(File file) {
  if (file.isDirectory())
   return true;
  String fileName = file.getName();
  int index = fileName.lastIndexOf('.');
  if (index > 0 && index < fileName.length() - 1) {
   String extension = fileName.substring(index + 1).toLowerCase();
   if (extension.equals(ext) || extension.equals(ext2))
    return true;
  }
  return false;
 }
//描述
 public String getDescription() {
  if (ext.equals("java"))
   return "JAVA Source File (*.java)";
  if (ext.equals("xls") && ext2.equals("xlsx"))
   return "JAVA Source File (*.xls/.xlsx)";
  return "";
 }
}
 
 

结合Poi实现可读取Excel的文件选择对话框的更多相关文章

  1. Java小知识----POI事件模式读取Excel 2007

    一.知识背景 1.读取excel的方法选择问题 java中读excel中的时间,我们通常用POI去解析,在使用new HSSFWorkbook(NEW FileInputStream(excelFil ...

  2. 前端读取Excel报表文件 js-xlsx

    1.http://www.cnblogs.com/imwtr/p/6001480.html (前端读取Excel报表文件) 2.https://github.com/SheetJS/js-xlsx

  3. python读取Excel表格文件

    python读取Excel表格文件,例如获取这个文件的数据 python读取Excel表格文件,需要如下步骤: 1.安装Excel读取数据的库-----xlrd 直接pip install xlrd安 ...

  4. 利用JFileChooser实现文件选择对话框

    简单的文件选择对话框: package mypackage;/** * 打开文件和存储文件 */import java.awt.BorderLayout;import java.awt.Contain ...

  5. VBScript - 弹出“文件选择对话框”方法大全!

    本文记录,VBScript 中,各种打开 "文件选择对话框" 的方法. 实现方法-1 (mshta.exe): 首先,我们要实现的就是,弹出上面的这个"文件选择对话框&q ...

  6. 文件选择对话框:CFileDialog

    程序如下: CString   FilePathName; //文件名参数定义 CFileDialog  Dlg(TRUE,NULL,NULL,                             ...

  7. NX二次开发-UFUN文件选择对话框UF_UI_create_filebox

    NX11+VS2013 #include <uf.h> #include <uf_ui.h> UF_initialize(); //文件选择对话框 char sPromptSt ...

  8. 使用Apache下poi创建和读取excel文件

    一:使用apache下poi创建excel文档 @Test /* * 使用Apache poi创建excel文件 */ public void testCreateExcel() { // 1:创建一 ...

  9. POI原生导入读取EXCEL

    好久没用 最近项目有冲突 所以又用到了这个 谁知道以后还会不会用 先记下来吧 直接扔项目里 调方法就OK 了. 记录一下....不想再写类似这样的东西了 import org.apache.poi.h ...

随机推荐

  1. WPF 依赖附加属性

    附加属性的本质是一个依赖属性,与普通的依赖属性区别: 1:注册方法名不一样,如 DependencyProperty.RegisterAttached 2:没有普通的属性包装器,而是通过get和set ...

  2. 2.Jmeter 快速入门教程(二)--创建简单web测试 打印 E-mail

    今天我们就来实际用Jmeter创建一个测试场景,并进行性能测试. 注:由于本人使用中文版本,使用英文版本的请注意具体的菜单及参数名称. 1. 添加线程组(相当于lr里的scenario 设置) 打开j ...

  3. (1.1)学习笔记之mysql体系结构(内存、进程、线程)

    关键词:mysql体系结构 参考:https://www.cnblogs.com/zhoubaojian/articles/7866292.html 一.mysql体系架构概述 1.mysql体系结构 ...

  4. git 处于游离的状态的解决办法

    在idea下将代码回退到某一历史版本,修改后push提醒detaced head,即处于游离状态,使用 git branch命令(辅助git status查看提交状态)查看: 在git bash下切换 ...

  5. springCloud的使用01-----服务的注册和发现

    1 搭建eureka注册服务器 1.1 创建springboot项目,导入相应的jar包依赖 <project xmlns="http://maven.apache.org/POM/4 ...

  6. MOV EAX,DWORD PTR SS:[EBP+8]

    nasm来写可以写成mov eax,dword ptr [ebp + 8]理由:ebp和esp默认是ss段,所以根本不用显式说明.          eax,ebx,ecx,edx,edi,esi默认 ...

  7. JS基础API

    数据类型 number object string null undefined boolean 转换规则是除了undefined null false 0 NAN ''或""&q ...

  8. svndumpfilter - 过滤一个 Subversion 仓库的转储文件 `dumpfile'。

    SYNOPSIS 总览 svndumpfilter command [options & args] OVERVIEW 概述 Subversion 是一个版本控制系统,允许保存旧版本的文件和目 ...

  9. KiCAD实用操作

    KiCAD实用操作之一:自动编辑线宽 今天偶然间发现的一个比较实用的功能,算是KiCAD的一个优点吧(或许是在AD上面没发现):当整个PCB布完线或者在布线过程中,我们有可能需要对某个线的宽度进行调整 ...

  10. LSI 9271阵列卡开启JBOD!

    1.开机等待读取到RAID卡后按ctrl+y(进入阵列卡命令符界面) 2.输入AdpSetProp EnableJBOD 1 -a0(开启JBOD功能) AdpSetProp EnableJBOD 0 ...