JTable экспорт в excel - Java
Формулировка задачи:
Здравствуйте, подскажите кто знает как экспортировать пустые ячейки JTable в Excel, т.е. у меня есть таблица в которой заполнены не все ячейки, при экспорте такой таблицы появляется ошибка соответственно ругается на то что не вся таблица заполнена. А добавлять в каждую ячейку нули и потом их удалять в excel не очень то и охота. вот сам код экспорта и метод который вызывает этот класс
java.lang.NullPointerException
at javaapplication120.ExcelExporterProduction.exportTable(ExcelExporterProduction.java:63)
at javaapplication120.DIpp.jMenuItem1ActionPerformed(DIpp .java:3044)
at javaapplication120.DIpp.access$3000(DIpp .java:44)
at javaapplication120.DIpp$39.actionPerformed(DIpp .java:1212)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.AbstractButton.doClick(AbstractButton.java:376)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:833)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:877)
at java.awt.Component.processMouseEvent(Component.java:6533)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6298)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication120;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JTable;
import javax.swing.table.TableModel;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
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.ss.util.RegionUtil;
/**
*
* @author admin
*/
class ExcelExporterProduction {
ExcelExporterProduction() {
}
public void exportTable(JTable jTable1, File file) throws IOException {
FileOutputStream out = null;
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");
int colCount = jTable1.getColumnCount();
int colRow = jTable1.getRowCount();
Row row = null;
Cell cell = null;
TableModel model = jTable1.getModel();
out = new FileOutputStream(file);
String a[] = {"Наименование", "ед.изм"};
//экспорт заголовка таблицы
sheet.shiftRows(0, jTable1.getColumnCount(), 1);
sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 0));
sheet.addMergedRegion(new CellRangeAddress(0, 1, 1, 1));
for (int j = 0; j <= jTable1.getRowCount(); j++) {
row = sheet.createRow(j);
for (int i = 0; i < model.getColumnCount(); i++) {
cell = row.createCell(i);
cell.setCellValue(model.getColumnName(i).toString());
}
}
sheet.addMergedRegion(new CellRangeAddress(0, 0, 2, 3));
sheet.addMergedRegion(new CellRangeAddress(0, 0, 4, 5));
sheet.addMergedRegion(new CellRangeAddress(0, 0, 6, 7));
sheet.addMergedRegion(new CellRangeAddress(0, 0, 8, 9));
//экспорт данных из таблицы в ексель
for (int i = 0; i < jTable1.getRowCount(); i++) {
row = sheet.createRow(i + 2);
int f = jTable1.getColumnCount();
for (int j = 0; j < jTable1.getColumnCount(); j++) {
cell = row.createCell(j);
cell.setCellValue(jTable1.getValueAt(i, j).toString());
}
}
for (int k = 0; k < 1; k++) {
row = sheet.createRow(k);
for (int j = 0; j < 12; j++) {
if (j < 2) {
cell = row.createCell(j);
cell.setCellValue(a[j].toString());
} else {
cell = row.createCell(j);
switch (j) {
case 2:
cell.setCellValue("Остаток");
break;
case 4:
cell.setCellValue("Приход(ДТ)");
break;
case 6:
cell.setCellValue("Расход(КТ)");
break;
case 8:
cell.setCellValue("Остаток");
break;
default:
break;
}
}
}
}
//прорисовка границ в ексель
for (int y = 0; y <= colRow + 1; y++) {
for (int x = 0; x < colCount; x++) {
CellRangeAddress range = new CellRangeAddress(y, y, x, x);
RegionUtil.setBorderTop(CellStyle.BORDER_THIN, range, sheet, wb);
RegionUtil.setBorderRight(CellStyle.BORDER_THIN, range, sheet, wb);
RegionUtil.setBorderBottom(CellStyle.BORDER_THIN, range, sheet, wb);
RegionUtil.setBorderLeft(CellStyle.BORDER_THIN, range, sheet, wb);
}
}
for (int i = 0; i < colCount - 1; i++) {
setBorder(colRow, colCount);
sheet.autoSizeColumn(i);
}
sheet.setColumnWidth(0, 4000);
sheet.setVerticallyCenter(Boolean.TRUE);
wb.write(out);
out.close();
}
private void setBorder(int i, int j) {
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");
for (int y = 0; y <= i; y++) {
for (int x = 0; x < j; x++) {
CellRangeAddress range = new CellRangeAddress(y, y, x, x);
RegionUtil.setBorderTop(CellStyle.BORDER_THIN, range, sheet,
wb);
RegionUtil.setBorderRight(CellStyle.BORDER_THIN, range, sheet,
wb);
RegionUtil.setBorderBottom(CellStyle.BORDER_THIN, range, sheet,
wb);
RegionUtil.setBorderLeft(CellStyle.BORDER_THIN, range, sheet,
wb);
}
}
}
} try {
JFileChooser fileChooser = new JFileChooser();
int retval = fileChooser.showSaveDialog(jButton1);
if (retval == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (file != null) {
if (!file.getName().toLowerCase().endsWith(".xls")) {
file = new File(file.getParentFile(), file.getName() + ".xls");
}
try {
ExcelExporterProduction exp = new ExcelExporterProduction();
exp.exportTable(jTable2, file);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("not found");
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}Решение задачи: «JTable экспорт в excel»
textual
Листинг программы
cell.setCellValue(jTable1.getValueAt(i, j).toString());