第一步: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. 查看.Net Framework的版本(PC和WinCE)

    一.在电脑上查看.Net Framework的版本 (1)第一步: 打开“我的电脑“,在地址栏输入 %systemroot%\Microsoft.NET\Framework 第二步:从列出来的文件夹中 ...

  2. 这 17 个 JVM 参数,高级 Java 必须掌握!

    作者:SimpleSmile https://www.cnblogs.com/Simple-Object/p/10272326.html前言 大家都知道,jvm在启动的时候,会执行默认的一些参数.一般 ...

  3. 使用IDEA快速搭建Springboot项目

    Spring Boot是由Pivotal团队提供的全新框架,设计目的是用来简化新Spring应用的初始搭建以及开发过程.它主要推崇的是'消灭配置’,实现零配置. 下面就介绍一下如何使用idea快速搭建 ...

  4. ubuntu 设置root密码

  5. String转list

    String l = "63, 47, 51, 35, 36, 52, 37, 53, 38, 54, 39, 55, 40, 56, 41, 57, 42";List<In ...

  6. Lambda select 动态字段

    直接上代码 //测试数据 public static List<User> myList = new List<User>() { , Name=,IsChild=false} ...

  7. 在AndroidStudio2.3.2下JNI开发的详细步骤(转)

    转自:http://blog.csdn.net/luhaoying1111/article/details/72468867 安装NDK 在工具栏点击File->Settings->App ...

  8. spring boot 与微服务之间的关系

    Spring Boot 和微服务没关系, Java 微服务治理框架普遍用的是 Spring Cloud. Spring Boot 产生的背景,是开发人员对 Spring 框架越来越复杂的配置吐槽越来越 ...

  9. obj.offsetHeight与obj.style.height $(obj).height()与$(obj).css('height')

    相同:都可以获取obj的高度区别:(1)obj.offsetHeight可以获取外部.内嵌和内联中定义的高,而obj.style.height只能获取内联中定义的高:(2)obj.offsetHeig ...

  10. Android中当数据库需要更新时我们该怎么办?

    问题:Android数据库更新并保留原来的数据如何实现 Andoird的SQLiteOpenHelper类中有一个onUpgrade方法.帮助文档中只是说当数据库升级时该方法被触发.经过实践,解决了我 ...