用java语言展示Excel文件内容

1、需要借助包来获取表中的行列、单元格等

2、把需要用到的包导入到工程项目里面(注意:如果用的是jxl.jar包,当读取后缀名为.xlsx时会报出Unable to recognize OLE stream的错误,本人用的就是这个包,所以只局限于读取后缀名为.xls的Excel)

3、代码如下:

1)、界面的设置

/**
 * @author
 * @vision createtime:2016下午8:10:59
 */
package ReadExcelSurface;

import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;

import ReadExcelControl.ButtonListener;
import ReadExceluntil.ReadMath;

/**
 * @author Administrator
 *
 */
public class ReadExcel extends JFrame {
	public static void main(String[] args) {
		new ReadExcel().initExcel();
	}

	private void initExcel() {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.setSize(ReadMath.width, ReadMath.height);
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(3);
		this.setUndecorated(true);
		this.assembly();
		this.setVisible(true);
		this.addMouseListener(mouse);
		this.addMouseMotionListener(mouse);
		// this.setExtendedState(Frame.ICONIFIED);
	}

	// 添加组件
	private void assembly() {
		JPanel panel = new JPanel() {
			@Override
			protected void paintComponent(Graphics g) {
				super.paintComponent(g);
				g.drawImage(new ImageIcon(loadImage("BallBackground.jpg"))
						.getImage(), 0, 0, this.getWidth(), this.getHeight(),
						null);
			}
		};
		panel.setLayout(null);
		this.add(panel);

		JLabel label1 = new JLabel(new ImageIcon(loadImage("缩小.png")));
		JLabel label2 = new JLabel(new ImageIcon(loadImage("关闭按钮2.png")));
		label1.setBounds(this.getWidth() - 80, 5, 30, 30);
		label2.setBounds(this.getWidth() - 40, 5, 30, 30);

		JLabel labelContent = new JLabel();
		labelContent.setFont(new Font("楷体", 1, 16));
		labelContent.setForeground(Color.BLUE);
		labelContent
				.setText("版本提示(version):由于此项目只针对于Microsoft Office进行操作,所以只能读取Excel表(后缀名为xls),谢谢使用!");
		labelContent.setBounds(ReadMath.width - 550, 50, 500, 40);

		panel.add(labelContent);
		panel.add(label2);
		panel.add(label1);
		MouseAdapter ma = new MouseAdapter() {
			@Override
			public void mouseReleased(MouseEvent e) {
				super.mouseReleased(e);
				ReadExcel.this.setExtendedState(Frame.ICONIFIED);
			}
		};
		MouseAdapter adapter = new MouseAdapter() {
			@Override
			public void mouseReleased(MouseEvent e) {
				super.mouseReleased(e);
				System.exit(0);
			}
		};
		label1.addMouseListener(ma);
		label2.addMouseListener(adapter);

		// 主组件
		JTextField jtf = new JTextField();
		JButton button1 = new JButton("请选择文件");
		JButton button2 = new JButton("搜索文件内容");
		jtf.setOpaque(false);
		// jtf.setBorder(null);
		jtf.setFont(new Font("宋体", 0, 20));

		jtf.setBounds(ReadMath.width - 550, 100, 350, 35);
		button1.setBounds(ReadMath.width - 180, 100, 105, 35);
		button2.setBounds(ReadMath.width - 180, 140, 105, 35);

		panel.add(jtf);
		panel.add(button1);
		panel.add(button2);
		ButtonListener bl = new ButtonListener(panel, jtf);
		button1.addActionListener(bl);
		button2.addActionListener(bl);
	}

	MouseAdapter mouse = new MouseAdapter() {
		int pressx, pressy;

		public void mousePressed(java.awt.event.MouseEvent e) {
			pressx = e.getX();
			pressy = e.getY();
		};

		public void mouseDragged(java.awt.event.MouseEvent e) {
			int x1 = e.getXOnScreen();
			int y1 = e.getYOnScreen();
			ReadExcel.this.setLocation(x1 - pressx, y1 - pressy);
		};
	};
	
	private URL loadImage(String imgPath) {
		return Thread.currentThread().getContextClassLoader().getResource(imgPath);
	}
}
2)、监听器的设置

/**
 * @author
 * @vision createtime:2016上午11:30:03
 */
package ReadExcelControl;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;

import ReadExceluntil.ReadMath;

/**
 * @author Administrator
 *
 */
public class ButtonListener implements ActionListener{
	private JTextField jtf;
	private JPanel panel;
	public int row;
	public int column;
	public ButtonListener(JPanel panel,JTextField jtf) {
		this.panel = panel;
		this.jtf = jtf;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String command = e.getActionCommand();
		if("请选择文件".equals(command)){
			JFileChooser jfc = new JFileChooser();
			jfc.showOpenDialog(null);
			File file =  jfc.getSelectedFile();
			if(jfc.getSelectedFile()!=null){
				jtf.setText(file.getAbsolutePath());
			}        
		} else if("搜索文件内容".equals(command)){
			SelectExcel select = new SelectExcel();
			if(jtf.getText()!=null&&jtf.getText().endsWith(".xls")){
				Object[][] data = select.getContent(jtf.getText());
				if(data!=null && data.length > 0) {
					// 定义队列,用于存储列名
					ArrayList columnNames = new ArrayList();
					// 用于存储列类型
					List> columnClasses = new ArrayList>();
					
					Object[] columnNameArray = data[0];
					for(Object columnName : columnNameArray) {
						columnNames.add(columnName);
						columnClasses.add(String.class);
					}
					data = Arrays.copyOfRange(data, 1, data.length - 1);
					TableListener tl = new TableListener(data, columnNames, columnClasses);
					JTable table = new JTable(tl);
					table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
					table.setSelectionBackground(Color.PINK);
//					table.setColumnSelectionAllowed(false); 
//					table.setRowSelectionAllowed(false); 
//					table.getTableHeader().setReorderingAllowed(false);
					
					JScrollPane jsp = new JScrollPane(table);
					jsp.setBounds(ReadMath.width-575,180,550,500);
					table.setOpaque(false);
					jsp.setOpaque(false);
					jsp.getViewport().setOpaque(false);
					panel.add(jsp);
				}
			}
		}
	}

}
 
  
/**
 * @author
 * @vision createtime:2016下午9:42:18
 */
package ReadExcelControl;

import java.util.List;

import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;

/**
 * @author Administrator
 *
 */
public class TableListener implements TableModel{
	
	private Object[][] data;
	
	private List columnNames;
	
	private List> cloumnClasses;
	
	
	public TableListener(Object[][] data, List columnNames, List> cloumnClasses) {
		this.data = data;
		this.columnNames = columnNames;
		this.cloumnClasses = cloumnClasses;
	}

	@Override
	public int getRowCount() {
		return data.length;
	}

	@Override
	public int getColumnCount() {
		if(data != null && data.length > 0) {
			return data[0].length;
		}
		return 0;
	}

	@Override
	public String getColumnName(int columnIndex) {
		if(columnNames!=null && !columnNames.isEmpty()) {
			if(columnIndex >= columnNames.size()) {
				return "";
			}
		}
		return String.valueOf(columnNames.get(columnIndex));
	}

	@Override
	public Class getColumnClass(int columnIndex) {
		if(cloumnClasses!=null && !cloumnClasses.isEmpty()) {
			if(columnIndex >= cloumnClasses.size()) {
				return null;
			}
		}
		return cloumnClasses.get(columnIndex);
	}

	@Override
	public boolean isCellEditable(int rowIndex, int columnIndex) {
		return true;
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		return data[rowIndex][columnIndex];
	}

	@Override
	public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
		data[rowIndex][columnIndex] = aValue;
	}

	@Override
	public void addTableModelListener(TableModelListener l) {
		
	}

	@Override
	public void removeTableModelListener(TableModelListener l) {
		
	}

}
 
  
3)、读取Excel表中内容的流程

/**
 * @author
 * @vision createtime:2016下午5:18:37
 */
package ReadExcelControl;


import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

/**
 * @author Administrator 通过java读取Excel表中的内容 并把其数据还原出来 需要用到的包jxl.jar包(网上下载)
 *
 */
public class SelectExcel {
	// 获取excel内容
	public Object[][] getContent(String path) {
		try {
			String content = "";
			// 创建文件输入流,读取文件内容
			FileInputStream fis = new FileInputStream(path);
			// 创建对象(类似于StringBuffer),它比StringBuffer要快
			StringBuilder sb = new StringBuilder();
			// 从输入流中创建Workbook对象,可以通过该对象来访问Excel表中的数据
			Workbook wb = Workbook.getWorkbook(fis);
			// 通过调用getsheets方法来获取工作表
			Sheet[] sheets = wb.getSheets();
			if(sheets.length <= 0) {
				return null;
			}
			List> result = new ArrayList>();
			
			for (int i = 0; i < sheets.length; i++) {
				// getsheet方法获取指定工作表
				Sheet sheet = wb.getSheet(i);
				// 遍历表中的内容
				for (int j = 0; j < sheet.getRows(); j++) {
					// 得到指定行
					List rowData = new ArrayList();
					Cell[] cell = sheet.getRow(j);
					for (int k = 0; k < cell.length; k++) {
						// 添加每一个单元格的数据
						rowData.add(cell[k].getContents());
					}
					result.add(rowData);
				}
			}
			fis.close();
			return convert2Array(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private Object[][] convert2Array(List> dataList) {
		if(dataList == null || dataList.isEmpty()) {
			return null;
		}
		Object[][] result = new Object[dataList.size()][];
		int size = dataList.size();
		List dataRow = null;
		for(int i=0; i 
  


4)、参数类的设置

/**
 * @author
 * @vision createtime:2016下午8:52:52
 */
package ReadExceluntil;

/**
 * @author Administrator
 *
 */
public class ReadMath {
	public static int width = 600;
	public static int height = 700;
}


上述代码可以生成的界面和功能如下所示:


可以实现拖动功能,点击"请选择文件"可以弹出一个文件选择框,选择一个文件,前提是后缀名必须是.xls的,这个本人已经做出了判断,避免会报出错误,当选择后,文件的路径会生成到文本输入框中,这个我没有设置文本输入框不可操作,大家可以设置一下,下一步,点击"搜索文件内容是",会展现一个JTable组件,显示Excel表中的内容,具体如下:







此项目还有不足的地方,还请大家包涵,谢谢观看!


你可能感兴趣的:(java)