Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I have a excel sheet with cell values like
" This is a bold text".
And i want to display it on JTextPane.I think i has something to do with RichTextString and StyledDocument of JTextPane but i am not sure, please help me with this.
Your option is to write the retrieved cell value from the excel as an html to JTextPane.
I have previously referred to this example to extract the html format of the cell values from an excel - works like a charm every time.
I have extended the code to include JTextPane option to display your cell contents.
Basic Code:
static boolean boldsie = false;
public static void main(String... args) {
File excel = new File("\\test.xlsx");
FileInputStream fis;
try {
fis = new FileInputStream(excel);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet ws = wb.getSheet("Sheet1");
int rowNum = ws.getLastRowNum() + 1;
int colNum = ws.getRow(0).getLastCellNum();
String[][] data = new String[rowNum][colNum];
for (int i = 0; i < rowNum; i++) {
XSSFRow row = ws.getRow(i);
for (int j = 0; j < colNum; j++) {
XSSFCell cell = row.getCell(j);
String value = cell.toString();
data[i][j] = value;
showDataInTextPane(ws, cell.getReference());
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void showDataInTextPane(XSSFSheet ws, String reference) {
JFrame frame = new JFrame("Formatted POI Sample");
Container content = frame.getContentPane();
JPanel panel = new JPanel();
JTextPane textPane = new JTextPane();
textPane.setContentType("text/html");
textPane.setText(getHtmlFromExcel(ws, reference));
panel.setLayout(new BorderLayout());
panel.add(textPane);
content.add(panel);
frame.setSize(100, 100);
frame.setVisible(true);
}
public static String getHtmlFromExcel(XSSFSheet sheet, String cellName) {
CellReference cellReference = new CellReference(cellName);
XSSFRow row = sheet.getRow(cellReference.getRow());
XSSFCell cell = row.getCell(cellReference.getCol());
XSSFRichTextString cellText = cell.getRichStringCellValue();
String htmlCode = "";
for (int i = 0; i < cellText.numFormattingRuns(); i++) {
try {
htmlCode += getFormatFromFont(cellText.getFontAtIndex(i));
} catch (NullPointerException ex) {
}
try {
htmlCode += getFormatFromFont(cellText
.getFontOfFormattingRun(i));
} catch (NullPointerException ex) {
}
htmlCode += cellText.getString().substring(
cellText.getIndexOfFormattingRun(i),
cellText.getIndexOfFormattingRun(i)
+ cellText.getLengthOfFormattingRun(i));
}
if (boldsie) {
htmlCode += "</b>";
boldsie = false;
}
return htmlCode;
}
private static String getFormatFromFont(XSSFFont font) {
String formatHtmlCode = "";
if (font.getBold() && !boldsie) {
formatHtmlCode += "<b>";
boldsie = true;
} else if (!font.getBold() && boldsie) {
formatHtmlCode += "</b>";
boldsie = false;
}
return formatHtmlCode;
}
Output:
You can extend per your need to make it more generic, align to the best practices and include other formats like italics etc.
Related
In my application, I have exported the table content to Excel already, but the result excludes the table header. Wondering how to export JTable to Excel include the table header? I tried couple ways, but still can not see the table header in excel, the following is my code:
defautTableModel = new DefaultTableModel(null,columnNames){
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
// the jTable row are generated dynamically.
final JTable jTable = new JTable(defautTableModel);
jTable.setLocation(20,60);
jTable.setSize(950,450);
jTable.setRowHeight(25);
JTableHeader jTableHeader = jTable.getTableHeader();
jTableHeader.setLocation(20,30);
jTableHeader.setSize(950,30);
jTableHeader.setFont(new Font(null, Font.BOLD, 16));
jTableHeader.setResizingAllowed(true);
jTableHeader.setReorderingAllowed(true);
jTable.add(jTableHeader);
JScrollPane tablePanel = new JScrollPane(jTable);
tablePanel.setLocation(10,10);
tablePanel.setSize(960,400);
// export data to excel method
public void exportToExcel(){
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
for (int i = 0; i < defautTableModel.getRowCount(); i++) {
Row = sheet.createRow(i);
for (int j = 0; j < defautTableModel.getColumnCount(); j++) {
Cell = Row.createCell(j);
try {
if (defautTableModel.getValueAt(i,j) != null){
Cell.setCellValue(defautTableModel.getValueAt(i,j).toString());
FileOutputStream fileOut = new FileOutputStream(Constant.Path_TestData_Output);
wb.write(fileOut);
fileOut.flush();
fileOut.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
You are only accessing the data columns and you need to get the header ones first.
You can acheive it by different means, either you use the method getColumnName
as ThomasEdwin mentioned in his comment or use columnNames variable that you have provided to your model constructor: new DefaultTableModel(null,columnNames)
Hope it helps
Export Java Swing JTable header with JTable index to Excel
private static void writeToExcell(DefaultTableModel TabR ,TableColumnModel tableM) throws IOException {
try
{
JFileChooser fileChooser = new JFileChooser();
int retval = fileChooser.showSaveDialog(fileChooser);
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");
#SuppressWarnings("resource")
Workbook wb = new HSSFWorkbook();
#SuppressWarnings("unused")
CreationHelper createhelper = wb.getCreationHelper();
org.apache.poi.ss.usermodel.Sheet sheet = wb.createSheet();
org.apache.poi.ss.usermodel.Row row = null;
org.apache.poi.ss.usermodel.Cell cell = null;
for (int a=0;a<TabR.getRowCount();a++)
{
row = sheet.createRow(a+1); /* We create an Excel layer Row.
We understand how many rows are in
TabR with GetRowCount from TabR, the
DefaultTableModel of the current JTable,
and add one to it.*/
for (int b=0;b<tableM.getColumnCount();b++)
{
cell = row.createCell(b);/* With the GetColumnCount
function of the existing JTable's
TableColumnModel, we create more
Column in the JTable.*/
cell.setCellValue(TabR.getValueAt(a, b).toString()); /*we give the value of the cell. */
}
}
for (int c=0;c<cell.getRowIndex();c++)
{
row = sheet.createRow(c);
for (int d=0;d<tableM.getColumnCount();d++)
{
cell = row.createCell(d);
cell.setCellValue(tableM.getColumn(d).getHeaderValue().toString());
}
}
FileOutputStream out = new FileOutputStream(file);
wb.write(out);
out.close();
}
}
}
} catch (FileNotFoundException ex) {
Logger.getLogger(B_anaEk.class.getName()).log(Level.ALL, null, ex);
} catch (IOException ex) {
Logger.getLogger(B_anaEk.class.getName()).log(Level.ALL, null, ex);
}
This question already has answers here:
How to read and write excel file
(22 answers)
Closed 5 years ago.
I am trying to write the data from table format to to Excel sheet,during this date is shown as "#######" in excel.But while i increasing the cell size the date is visible correctly.So i want to increase the width size of the excel file from the code itself.Is anyone can help me ?The code is below`
JButton btnExport = new JButton("Export To Excel");
btnExport.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e1) {
btnExport.setMnemonic(KeyEvent.VK_X);
btnExport.addActionListener(new AksyonListener());
}
public void toExcel(JTable table1, File file) {
try {
System.out.println("Success");
FileWriter excel = new FileWriter(file);
// DefaultTableModel model = new DefaultTableModel();
// table.setModel(model);
// model.insertRow(table.getRowCount(), new Object[]{0});
for (int i = 0; i < table.getColumnCount(); i++) {
excel.write(table.getColumnName(i) + "\t");
System.out.println(table.getColumnName(i));
}
/* int d,f;
System.out.println("d: "+table.getRowCount());
System.out.println("f: "+table.getColumnCount());*/
excel.write("\n");
for (int i = 1; i < table.getRowCount(); i++) {
for (int j = 0; j < table.getColumnCount(); j++) {
excel.write(table.getValueAt(i, j) + "\t");
System.out.println(table.getValueAt(i, j));
}
excel.write("\n");
}
excel.close();
} catch (IOException e) {
System.out.println(e);
}
}
class AksyonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnExport) {
JFileChooser fc = new JFileChooser();
int option = fc.showSaveDialog(TableSortFilter.this);
if (option == JFileChooser.APPROVE_OPTION) {
String filename = fc.getSelectedFile().getName();
String path = fc.getSelectedFile().getParentFile().getPath();
int len = filename.length();
String ext = "";
String file = "";
if (len > 4) {
ext = filename.substring(len - 4, len);
}
if (ext.equals(".xls")) {
file = path + "\\" + filename;
} else {
file = path + "\\" + filename + ".xls";
}
toExcel(table, new File(file));
}
}
}
}
});
Try to use apache poi to export and create excel
https://poi.apache.org/
I am new to Apache POI.
I have written a small code for removing duplicate records from a excel file. I am successfully able to identify the duplicate records across sheets but when writing to a new file after removing records, no output is being generated.
Please help where I am goin wrong?
Am I writing properly ?? Or am missing something?
public static void main(String args[]) {
DataFormatter formatter = new DataFormatter();
HSSFWorkbook input_workbook;
HSSFWorkbook workbook_Output_Final;
HSSFSheet input_workbook_sheet;
HSSFRow row_Output;
HSSFRow row_1_index;
HSSFRow row_2_index;
String value1 = "";
String value2 = "";
int count;
//main try catch block starts
try {
FileInputStream input_file = new FileInputStream("E:\\TEST\\Output.xls"); //reading from input file
input_workbook = new HSSFWorkbook(new POIFSFileSystem(input_file));
for (int sheetnum = 0; sheetnum < input_workbook.getNumberOfSheets(); sheetnum++) { //traversing sheets
input_workbook_sheet = input_workbook.getSheetAt(sheetnum);
int input_workbook_sheet_total_row = input_workbook_sheet.getLastRowNum(); //fetching last row nmber
for (int input_workbook_sheet_row_1 = 0; input_workbook_sheet_row_1 <= input_workbook_sheet_total_row; input_workbook_sheet_row_1++) { //traversing row 1
for (int input_workbook_sheet_row_2 = 0; input_workbook_sheet_row_2 <= input_workbook_sheet_total_row; input_workbook_sheet_row_2++) {
row_1_index = input_workbook_sheet.getRow(input_workbook_sheet_row_1); //fetching one iteration row index
row_2_index = input_workbook_sheet.getRow(input_workbook_sheet_row_2); //fetching sec iteration row index
if (row_1_index != row_2_index) {
count = 0;
value1 = "";
value2 = "";
for (int row_1_index_cell = 0; row_1_index_cell < row_1_index.getLastCellNum(); row_1_index_cell++) { //traversing cell for each row
try {
value1 = value1 + formatter.formatCellValue(row_1_index.getCell(row_1_index_cell)); //fetching row cells value
value2 = value2 + formatter.formatCellValue(row_2_index.getCell(row_1_index_cell)); //fetching row cells value
} catch (NullPointerException e) {
}
count++;
if (count == row_1_index.getLastCellNum()) {
if (value1.hashCode() == value2.hashCode()) { //remove the duplicate logic
System.out.println("deleted : " + row_2_index);
System.out.println("------------------");
input_workbook_sheet.removeRow(row_2_index);
}
}
}
}
}
}
}
FileOutputStream fileOut = new FileOutputStream("E:\\TEST\\workbook.xls");
input_workbook.write(fileOut);
fileOut.close();
input_file.close();
} catch (Exception e) {
//e.printStackTrace();
}
//main try catch block ends
}
A couple of things to note:
you swallow any kind of Exception; Igotsome nullpointers with my test data, and that would prevent the workbook from being written
when removing rows, it is an old trick to move backwards through the row numbers because then you don't have to adjust for the row number you have just removed
the code empties the row, but it doesn't move all rows upwards (=there is a gap after the delete). If you want to remove that gap, you can work with shiftRows
you compare things by hashcode, which is possible (in some use cases), but I feel like .equals() is what you want to do. See also Relationship between hashCode and equals method in Java
Here's some code that worked for my test data, feel free to comment if something doesn't work with your data:
public static void main(String args[]) throws IOException {
DataFormatter formatter = new DataFormatter();
HSSFWorkbook input_workbook;
HSSFWorkbook workbook_Output_Final;
HSSFSheet input_workbook_sheet;
HSSFRow row_Output;
HSSFRow row_1_index;
HSSFRow row_2_index;
String value1 = "";
String value2 = "";
int count;
FileInputStream input_file = new FileInputStream("c:\\temp\\test.xls");
input_workbook = new HSSFWorkbook(new POIFSFileSystem(input_file));
for (int sheetnum = 0; sheetnum < input_workbook.getNumberOfSheets(); sheetnum++) {
input_workbook_sheet = input_workbook.getSheetAt(sheetnum);
int input_workbook_sheet_total_row = input_workbook_sheet.getLastRowNum();
for (int input_workbook_sheet_row_1 = input_workbook_sheet_total_row; input_workbook_sheet_row_1 >=0; input_workbook_sheet_row_1--) { // traversing
for (int input_workbook_sheet_row_2 = input_workbook_sheet_total_row; input_workbook_sheet_row_2 >= 0 ; input_workbook_sheet_row_2--) {
row_1_index = input_workbook_sheet.getRow(input_workbook_sheet_row_1);
row_2_index = input_workbook_sheet.getRow(input_workbook_sheet_row_2);
if (row_1_index != null && row_2_index != null && row_1_index != row_2_index) {
count = 0;
value1 = "";
value2 = "";
int row_1_max = row_1_index.getLastCellNum() - 1;
for (int row_1_index_cell = 0; row_1_index_cell < row_1_max; row_1_index_cell++) {
try {
value1 = value1 + formatter.formatCellValue(row_1_index.getCell(row_1_index_cell));
value2 = value2 + formatter.formatCellValue(row_2_index.getCell(row_1_index_cell));
} catch (NullPointerException e) {
e.printStackTrace();
}
count++;
if (value1.equals(value2)) {
System.out.println("deleted : " + row_2_index.getRowNum());
System.out.println("------------------");
input_workbook_sheet.removeRow(row_2_index);
input_workbook_sheet.shiftRows(
row_2_index.getRowNum() + 1,
input_workbook_sheet_total_row,
-1,
true,
true);
}
}
}
}
}
}
FileOutputStream fileOut = new FileOutputStream("c:\\temp\\workbook.xls");
input_workbook.write(fileOut);
fileOut.close();
input_file.close();
input_workbook.close();
}
I want to run selenium-webdriver-java-eclipse, using excel file contains multiple excel sheets with different name(sheet1,sheet2,sheet3,...), i need a for loop help me to do that and read from this sheets.
public class ExcelDataConfig {
XSSFWorkbook wb;
XSSFSheet sheet = null;
public ExcelDataConfig(String Excelpath) throws IOException {
// TODO Auto-generated method stub
try {
File file = new File(Excelpath);
// Create an object of FileInputStream class to read excel file
FileInputStream fis = new FileInputStream(file);
wb = new XSSFWorkbook(fis);
} catch (Exception e) {
}
}
public String GetData(int sheetNumber, int Row, int Column) {
Iterator<Row> rowIt=sheet.rowIterator();
DataFormatter formatter = new DataFormatter();
XSSFCell cell = sheet.getRow(Row).getCell(Column);
String data = formatter.formatCellValue(cell);
return data;
}
public int GetRowCount(String sheetNumber) {
int row = wb.getSheet(sheetNumber).getLastRowNum();
row = row + 1;
return row;
}
}
try something like this, it is working for me you need to add the sheet numbers and cell numbers at the places of k and j
enter code here
String filePath="C:\\Users\\USER\\Desktop\\Book1.xlsx";// file path
FileInputStream fis=new FileInputStream(filePath);
Workbook wb=WorkbookFactory.create(fis);
ArrayList<String> ls=new ArrayList<String>();
for(int k=0; k<=3;k++)//k =sheet no
{
Sheet sh=wb.getSheetAt(k);
System.out.println(sh);
// int count=0;
for(int i=0;i<=sh.getLastRowNum();i++)
{
System.out.println("row no:"+i);
for(int j=0; j<=4;j++)//j=column no
{
try {
String values=sh.getRow(i).getCell(j).getStringCellValue().trim();
System.out.println(values);
//condetions
/* if(values.contains("condtn1"))
{
System.out.println("Value of cell "+values+" ith row "+(i+1));
ls.add(values);
count++;
}
if(values.contains("condn2"))
{
System.out.println("Value of cell "+values+" ith row "+(i+1));
ls.add(values);
count++;
}*/
}catch(Exception e){
}
}
}
}
}
}
Please try writing similar to something like this:
for (int i = startRow; i < endRow + 1; i++) {
for (int j = startCol; j < endCol + 1; j++) {
testData[i - startRow][j - startCol] = ExcelWSheet.getRow(i).getCell(j).getStringCellValue();
Cell cell = ExcelWSheet.getRow(i).getCell(j);
testData[i - startRow][j - startCol] = formatter.formatCellValue(cell);
}
}
Terms used in method are pretty self explanatory. Let us know if you get stuck or need more info.
I have a java application that exports some data to a spreadsheet using POI. The problem is that sometimes (not always) there are a couple of lines that have no information (they are "blank") but when I save the XLS document to my desktop and open it, the cells are filled with the correct information.
Im using POI 3.7.
Down here you have an example of what's happening.
[EDIT] - I add some code:
This is the method that insert the data into the sheet:
public void setTransactionDetailsData(HSSFSheet sheet, String[][] records){
HSSFRow rowContent = null;
HSSFCell cellContent = null;
String cell = "";
Integer recordNumber = records.length;
Integer columnNumber = records[0].length;
Integer nextDataIndex = 0;
String styleText = "";
boolean customStyles = styles.size()>0;
short alignment;
CellStyle cellStyle = null;
for(int i = 0; i<recordNumber;i++){
//New row
rowContent = sheet.createRow(lastRowCreated);
rowContent.setHeightInPoints((customDataCellHeight * sheet.getDefaultRowHeightInPoints()));
for(int j = 0; j<columnNumber;j++){
cellContent = null;
cellContent = rowContent.createCell((nextDataIndex));
cell = records[i][j];
if(customStyles){
try{
styleText = styles.get(nextDataIndex);
alignment = getAlignment(styleText);
}catch(IndexOutOfBoundsException e){
LOG.info("Error while obtaining style for position " +nextDataIndex+ ", max index is " +(styles.size()-1)+ ". Check the list of styles you send");
styleText = "";
alignment = 1;
}
}else{
alignment = 1;
}
cellStyle = getCellStyle(i,Integer.valueOf(alignment),styleText);
//Text
if("".equals(styleText) || "value_left".equals(styleText) || "value".equalsIgnoreCase(styleText)){
cellContent.setCellValue(cell);
}else{
if(isNumeric(cell)){
try{
cellContent.setCellValue(convertoToParseableNumber(cell));
cellContent.setCellType(0);
}catch(NumberFormatException e){
LOG.info("Error ocurred while parsing value " +cell+ " no number");
cellContent.setCellValue(cell);
}
}else{
cellContent.setCellValue(cell);
}
}
cellContent.setCellStyle(cellStyle);
nextDataIndex++;
}
//Back to first column
nextDataIndex = 0;
lastRowCreated++;
}
autosize(sheet);
}
Thank you in advance.