使用文件路径导入 Excel 文件
Import Excel File using file path
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class excelTojTable extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
static JTable table;
static JScrollPane scroll;
// header is Vector contains table Column
static Vector headers = new Vector();
static Vector data = new Vector();
// Model is used to construct
DefaultTableModel model = null;
// data is Vector contains Data from Excel File static Vector data = new Vector();
static JButton jbClick;
static JFileChooser jChooser;
static int tableWidth = 0;
// set the tableWidth
static int tableHeight = 0;
// set the tableHeight
public excelTojTable()
{
super("Import Excel To JTable");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel buttonPanel = new JPanel();
//buttonPanel.setBackground(Color.white);
/*
*
* jChooser = new JFileChooser();
jbClick = new JButton("Select Excel File");
buttonPanel.add(jbClick, BorderLayout.CENTER);
// Show Button Click Event
jbClick.addActionListener(new ActionListener()
{
@Override public void actionPerformed(ActionEvent arg0)
{
jChooser.showOpenDialog(null);
jChooser.setDialogTitle("Select only Excel workbooks");
File file = jChooser.getSelectedFile();
if(file==null)
{
JOptionPane.showMessageDialog(null, "Please select any Excel file.", "Help",JOptionPane.INFORMATION_MESSAGE);
return;
}
else if(!file.getName().endsWith("xls"))
{
JOptionPane.showMessageDialog(null, "Please select only Excel file.", "Error",JOptionPane.ERROR_MESSAGE);
}
else
{
fillData(file);
model = new DefaultTableModel(data, headers);
tableWidth = model.getColumnCount() * 150;
tableHeight = model.getRowCount() * 25;
table.setPreferredSize(new Dimension( tableWidth, tableHeight)); table.setModel(model);
}
}
}
);
*
*
*/
table = new JTable();
table.setAutoCreateRowSorter(true);
model = new DefaultTableModel(data, headers);
table.setModel(model);
table.setBackground(Color.pink);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setEnabled(false);
table.setRowHeight(25);
table.setRowMargin(4);
tableWidth = model.getColumnCount() * 150;
tableHeight = model.getRowCount() * 25;
table.setPreferredSize(new Dimension( tableWidth, tableHeight));
scroll = new JScrollPane(table); scroll.setBackground(Color.pink);
scroll.setPreferredSize(new Dimension(300, 300));
scroll.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
getContentPane().add(buttonPanel, BorderLayout.NORTH);
getContentPane().add(scroll, BorderLayout.CENTER);
setSize(600, 600);
setResizable(true); setVisible(true);
}
/** * Fill JTable with Excel file data. * * @param file * file :contains xls file to display in jTable */
void fillData(File file)
{
int index=-1;
HSSFWorkbook workbook = null;
try {
try {
FileInputStream inputStream = new FileInputStream (new File("C:\A.xls"));
workbook = new HSSFWorkbook(inputStream);
}
catch (IOException ex)
{
Logger.getLogger(excelTojTable.class. getName()).log(Level.SEVERE, null, ex);
}
String[] strs=new String[workbook.getNumberOfSheets()];
//get all sheet names from selected workbook
for (int i = 0; i < strs.length; i++)
{
strs[i]= workbook.getSheetName(i);
}
JFrame frame = new JFrame("Input Dialog");
String selectedsheet = (String) JOptionPane.showInputDialog(frame, "Which worksheet you want to import ?", "Select Worksheet",
JOptionPane.QUESTION_MESSAGE,
null,
strs,
strs[0]);
if (selectedsheet!=null)
{
for (int i = 0; i < strs.length; i++)
{
if (workbook.getSheetName(i).equalsIgnoreCase(selectedsheet))
index=i;
}
HSSFSheet sheet = workbook.getSheetAt(index);
HSSFRow row=sheet.getRow(0);
headers.clear();
for (int i = 0; i < row.getLastCellNum(); i++)
{
HSSFCell cell1 = row.getCell(i);
headers.add(cell1.toString());
}
data.clear();
for (int j = 1; j < sheet.getLastRowNum() + 1; j++)
{
Vector d = new Vector();
row=sheet.getRow(j);
int noofrows=row.getLastCellNum();
for (int i = 0; i < noofrows; i++)
{
//To handle empty excel cells
HSSFCell cell=row.getCell(i, org.apache.poi.ss.usermodel.Row.CREATE_NULL_AS_BLANK );
System.out.println (cell.getCellType());
d.add(cell.toString());
}
d.add("\n");
data.add(d);
}
}
else
{
return;
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args) {
new excelTojTable();
}
}
我想导入 Excel (.xls) 文件到 JTable,代码与 jChooser 一起工作正常,但我不需要使用它,我想直接使用文件路径实现这个过程.我尝试这样做,但它 return 为空。我的代码中的缺失点在哪里
the code works correctly with jChooser
文件选择器将提供完整的路径和目录;
FileInputStream inputStream = new FileInputStream (new File("C:\A.xls"));
我想您需要指定包含文件的正确目录。
因此使用文件选择器重新测试并添加调试代码以显示文件对象。然后获取该字符串值并创建您的 File 对象。这样你就知道你对路径进行了正确的编码。
问题是你为什么要这样做。您不应在程序中使用硬编码数据。
编辑:
所以基本上你需要重写ActionListener代码。逻辑应该是这样的:
File file = getFile();
System.out.println(file); // make sure the File object is the same in both cases.
fileData( file );
然后在 getFile()
方法中添加您的逻辑以获取 File 对象。首先,您可以尝试简单地 return 硬编码的 File 对象。然后您可以更改代码以从文件选择器中获取文件。如果您 return 同一个 File 对象是两种情况,那么代码将起作用。
The file which is only readable will be provided by me ..
在这种情况下,最简单的方法是将电子表格作为 embedded-resource and access it by URL. Once the URL is properly formed, get an input stream and load it using the HSSFWorkbook(InputStream, boolean)
构造函数提供。
有关获取正确 URL 的详细信息,请参阅 info. page for embedded resource。
请注意,嵌入资源不可用作 File
对象。
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class excelTojTable extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
static JTable table;
static JScrollPane scroll;
// header is Vector contains table Column
static Vector headers = new Vector();
static Vector data = new Vector();
// Model is used to construct
DefaultTableModel model = null;
// data is Vector contains Data from Excel File static Vector data = new Vector();
static JButton jbClick;
static JFileChooser jChooser;
static int tableWidth = 0;
// set the tableWidth
static int tableHeight = 0;
// set the tableHeight
public excelTojTable()
{
super("Import Excel To JTable");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel buttonPanel = new JPanel();
//buttonPanel.setBackground(Color.white);
/*
*
* jChooser = new JFileChooser();
jbClick = new JButton("Select Excel File");
buttonPanel.add(jbClick, BorderLayout.CENTER);
// Show Button Click Event
jbClick.addActionListener(new ActionListener()
{
@Override public void actionPerformed(ActionEvent arg0)
{
jChooser.showOpenDialog(null);
jChooser.setDialogTitle("Select only Excel workbooks");
File file = jChooser.getSelectedFile();
if(file==null)
{
JOptionPane.showMessageDialog(null, "Please select any Excel file.", "Help",JOptionPane.INFORMATION_MESSAGE);
return;
}
else if(!file.getName().endsWith("xls"))
{
JOptionPane.showMessageDialog(null, "Please select only Excel file.", "Error",JOptionPane.ERROR_MESSAGE);
}
else
{
fillData(file);
model = new DefaultTableModel(data, headers);
tableWidth = model.getColumnCount() * 150;
tableHeight = model.getRowCount() * 25;
table.setPreferredSize(new Dimension( tableWidth, tableHeight)); table.setModel(model);
}
}
}
);
*
*
*/
table = new JTable();
table.setAutoCreateRowSorter(true);
model = new DefaultTableModel(data, headers);
table.setModel(model);
table.setBackground(Color.pink);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setEnabled(false);
table.setRowHeight(25);
table.setRowMargin(4);
tableWidth = model.getColumnCount() * 150;
tableHeight = model.getRowCount() * 25;
table.setPreferredSize(new Dimension( tableWidth, tableHeight));
scroll = new JScrollPane(table); scroll.setBackground(Color.pink);
scroll.setPreferredSize(new Dimension(300, 300));
scroll.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
getContentPane().add(buttonPanel, BorderLayout.NORTH);
getContentPane().add(scroll, BorderLayout.CENTER);
setSize(600, 600);
setResizable(true); setVisible(true);
}
/** * Fill JTable with Excel file data. * * @param file * file :contains xls file to display in jTable */
void fillData(File file)
{
int index=-1;
HSSFWorkbook workbook = null;
try {
try {
FileInputStream inputStream = new FileInputStream (new File("C:\A.xls"));
workbook = new HSSFWorkbook(inputStream);
}
catch (IOException ex)
{
Logger.getLogger(excelTojTable.class. getName()).log(Level.SEVERE, null, ex);
}
String[] strs=new String[workbook.getNumberOfSheets()];
//get all sheet names from selected workbook
for (int i = 0; i < strs.length; i++)
{
strs[i]= workbook.getSheetName(i);
}
JFrame frame = new JFrame("Input Dialog");
String selectedsheet = (String) JOptionPane.showInputDialog(frame, "Which worksheet you want to import ?", "Select Worksheet",
JOptionPane.QUESTION_MESSAGE,
null,
strs,
strs[0]);
if (selectedsheet!=null)
{
for (int i = 0; i < strs.length; i++)
{
if (workbook.getSheetName(i).equalsIgnoreCase(selectedsheet))
index=i;
}
HSSFSheet sheet = workbook.getSheetAt(index);
HSSFRow row=sheet.getRow(0);
headers.clear();
for (int i = 0; i < row.getLastCellNum(); i++)
{
HSSFCell cell1 = row.getCell(i);
headers.add(cell1.toString());
}
data.clear();
for (int j = 1; j < sheet.getLastRowNum() + 1; j++)
{
Vector d = new Vector();
row=sheet.getRow(j);
int noofrows=row.getLastCellNum();
for (int i = 0; i < noofrows; i++)
{
//To handle empty excel cells
HSSFCell cell=row.getCell(i, org.apache.poi.ss.usermodel.Row.CREATE_NULL_AS_BLANK );
System.out.println (cell.getCellType());
d.add(cell.toString());
}
d.add("\n");
data.add(d);
}
}
else
{
return;
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args) {
new excelTojTable();
}
}
我想导入 Excel (.xls) 文件到 JTable,代码与 jChooser 一起工作正常,但我不需要使用它,我想直接使用文件路径实现这个过程.我尝试这样做,但它 return 为空。我的代码中的缺失点在哪里
the code works correctly with jChooser
文件选择器将提供完整的路径和目录;
FileInputStream inputStream = new FileInputStream (new File("C:\A.xls"));
我想您需要指定包含文件的正确目录。
因此使用文件选择器重新测试并添加调试代码以显示文件对象。然后获取该字符串值并创建您的 File 对象。这样你就知道你对路径进行了正确的编码。
问题是你为什么要这样做。您不应在程序中使用硬编码数据。
编辑:
所以基本上你需要重写ActionListener代码。逻辑应该是这样的:
File file = getFile();
System.out.println(file); // make sure the File object is the same in both cases.
fileData( file );
然后在 getFile()
方法中添加您的逻辑以获取 File 对象。首先,您可以尝试简单地 return 硬编码的 File 对象。然后您可以更改代码以从文件选择器中获取文件。如果您 return 同一个 File 对象是两种情况,那么代码将起作用。
The file which is only readable will be provided by me ..
在这种情况下,最简单的方法是将电子表格作为 embedded-resource and access it by URL. Once the URL is properly formed, get an input stream and load it using the HSSFWorkbook(InputStream, boolean)
构造函数提供。
有关获取正确 URL 的详细信息,请参阅 info. page for embedded resource。
请注意,嵌入资源不可用作 File
对象。