I managed to set label for my Excel, but I want to set values to cells which is an array and I want to set values with For loop but with this code my for loop doesn't work and label 4 and 5 don't write in my Excel file.
how can i set values to cells that those values change in every iteration?
String sdCard = getExternalFilesDir("/").getAbsolutePath();
File directory = new File(sdCard + "/MyFolder/");
//create directory if not exist
if(!directory.isDirectory()){
directory.mkdirs();
//Toast.makeText(getApplicationContext(),"dir",Toast.LENGTH_LONG).show();
}
//file path
File file = new File(directory, fileName);
WorkbookSettings wbSettings = new WorkbookSettings();
//wbSettings.setLocale(new Locale("en", "EN"));
WritableWorkbook workbook;
try {
int a = 1;
workbook = Workbook.createWorkbook(file, wbSettings);
//Toast.makeText(getApplicationContext(),"done4",Toast.LENGTH_LONG).show();
//Excel sheet name. 0 represents first sheet
WritableSheet sheet = workbook.createSheet("Mydata1", 0);
//Toast.makeText(getApplicationContext(),"done3",Toast.LENGTH_LONG).show();
Label label0 = new Label(0,0,"Date");
Label label1 = new Label(1,0,"time");
Label label2 = new Label(2,0,"xCor");
Label label3 = new Label(3,0,"score");
Label label7 = new Label(2,1,xCor[2]);
try {
sheet.addCell(label0);
sheet.addCell(label1);
sheet.addCell(label2);
sheet.addCell(label3);
for(int i3 = 1; i3==j+1 ; i3++) {
String text = xCor[i3];
sheet.getWritableCell(text);
Label label4 = new Label(2,i3,text);
Label label5 = new Label(1,i3,text);
sheet.addCell(label4);
sheet.addCell(label5);
}
sheet.addCell(label7);
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
workbook.write();
try {
workbook.close();
} catch (WriteException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
It is difficult to tell ...because variable a is unused, j and xCor are being defined nowhere.
But one cannot have i3 == j+1 as the run condition for a for loop, because the condition will never be true and therefore the execution will never enter that control flow statement (dead code).
Most commonly, one may want to compare the loop index with the smaller or equal operator:
for (int i=1; i <= j; i++) { ... }
Logging to console can greatly help to determine what a loop actually does, for example:
Log.d(LOG_TAG, "i3 = " + i3 );
Also see the JavaDocs ...assuming that this is jxl.write.
Alike this you might eventually learn how it works.
Related
Maybe "writing" wasn't the correct word since in this function, I am just setting the cells and then writing afterwards.
I have a function that I have pin pointed to be the cause of it bogging down. When it gets to this function, it spends over 10 minutes here before I just terminate it.
This is the function that I am passing an output_wb to:
private static void buildRowsByListOfRows(int sheetNumber, ArrayList<Row> sheet, Workbook wb) {
Sheet worksheet = wb.getSheetAt(sheetNumber);
int lastRow;
Row row;
String cell_value;
Cell cell;
int x = 0;
System.out.println("Size of array list: " + sheet.size());
for (Row my_row : sheet) {
try {
lastRow = worksheet.getLastRowNum();
row = worksheet.createRow(++lastRow);
for (int i = 0; i < my_row.getLastCellNum(); i++) {
cell_value = getCellContentAsString(my_row.getCell(i, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
cell = row.createCell(i);
cell.setCellValue(cell_value);
System.out.println("setting row #: " + x + "with value =>" + cell_value);
}
x++;
} catch (Exception e) {
System.out.println("SOMETHING WENT WRONG");
System.out.println(e);
}
}
}
The size of the ArrayList is 73,835. It starts off running pretty fast then it gets to around row 20,000 and it then you can see the print statements in the loop getting spread out further and further apart. Each row has 70 columns.
Is this function really written that poorly or is something else going on?
What can I do to optimize this?
I create the output workbook like this if this matters:
// Create output file with the required sheets
createOutputXLSFile(output_filename_path);
XSSFWorkbook output_wb = new XSSFWorkbook(new FileInputStream(output_filename_path));
And the createOutputXLSFile() looks like this:
private static void createOutputXLSFile(String output_filename_path) throws FileNotFoundException {
try {
// Directory path where the xls file will be created
// Create object of FileOutputStream
FileOutputStream fout = new FileOutputStream(output_filename_path);
XSSFWorkbook wb = new XSSFWorkbook();
wb.createSheet("Removed records");
wb.createSheet("Added records");
wb.createSheet("Updated records");
// Build the Excel File
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
wb.write(outputStream);
outputStream.writeTo(fout);
outputStream.close();
fout.close();
wb.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static String getCellContentAsString(Cell cell) {
DataFormatter fmt = new DataFormatter();
String data = null;
if (cell.getCellType() == CellType.STRING) {
data = String.valueOf(cell.getStringCellValue());
} else if (cell.getCellType() == CellType.NUMERIC) {
data = String.valueOf(fmt.formatCellValue(cell));
} else if (cell.getCellType() == CellType.BOOLEAN) {
data = String.valueOf(fmt.formatCellValue(cell));
} else if (cell.getCellType() == CellType.ERROR) {
data = String.valueOf(cell.getErrorCellValue());
} else if (cell.getCellType() == CellType.BLANK) {
data = String.valueOf(cell.getStringCellValue());
} else if (cell.getCellType() == CellType._NONE) {
data = String.valueOf(cell.getStringCellValue());
}
return data;
}
Update #1- Seems to be happening here. If I comment out all 3 lines then it finishes:
cell_value = getCellContentAsString(my_row.getCell(i, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
cell = row.createCell(i);
cell.setCellValue(cell_value);
Update #2 - If I comment out these two lines, then the loop finishes as expected:
cell = row.createCell(i); // The problem
cell.setCellValue(cell_value);
So now I know the problem is the row.createCell(i) but why? How can I optimize this?
I finally managed to resolve this issue. Turns out that using XSSF to write is just too slow if the files are large. So I converted the XSSF output workbook to an SXSSFWorkbook. To do that I just passed in my already existing XSSFWorkbook into SXSSFWorkbook like this :
// Create output file with the required sheets
createOutputXLSFile(output_filename_path);
XSSFWorkbook output_wb_temp = new XSSFWorkbook(new FileInputStream(output_filename_path));
SXSSFWorkbook output_wb = new SXSSFWorkbook(output_wb_temp);
The rest of the code works as is.
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);
}
I've a web project, where grid view is displayed from database. Arraylist name is leadSchoolList. So, I kept a button, when clicked it runs a method(named:-actionExportToExcel) in Struts action class. Right now I am able to export list elements to excel.
But the problem I'm facing is opening up that exported excel Sheet on window. So another method(named:-open) is called inside actionExportToExcel. But I don't know where I'm wrong, so can anyone help me?
public String actionExportToExcel(){
try {
FileOutputStream fileOut = new FileOutputStream("D:/poi-test.xls");
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
leadSchoolList = leadSchoolService.getAllLeadSchool();
for(int rowNum = 0; rowNum < leadSchoolList.size(); rowNum++){
HSSFRow row = sheet.createRow(rowNum);
//for(int colNum = 0; colNum < 5; colNum++ ){
HSSFCell cell1 = row.createCell(0);
LeadSchool leadSchool = leadSchoolList.get(rowNum);
cell1.setCellValue(leadSchool.getLeadSchool_String_LSchool_ID());
HSSFCell cell2 = row.createCell(1);
cell2.setCellValue(leadSchool.getLeadSchool_String_Name());
HSSFCell cell3 = row.createCell(2);
cell3.setCellValue(leadSchool.getLeadSchool_String_Address());
HSSFCell cell4 = row.createCell(3);
cell4.setCellValue(leadSchool.getLeadSchool_String_Phone_No());
HSSFCell cell5 = row.createCell(4);
cell5.setCellValue(leadSchool.getLeadSchool_String_Remarks());
System.out.println("Successfully exported to Excel");
}
try {
wb.write(fileOut);
// fileOut.flush();
open(fileOut);
//fileOut.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
addActionError("The process cannot access the file because it is being used by another process");
e.printStackTrace();
}
return SUCCESS;
}
private void open(FileOutputStream f) {
String[] cmd = new String[4];
try{
cmd[0] = "cmd.exe";
cmd[1] = "/C";
cmd[2] = "start";
cmd[3] = "D:/poi-test.xls";
Runtime.getRuntime().exec(cmd);
//Runtime.getRuntime().exec("cmd.exe /c start D:/poi-test.xls");
System.out.print("file opened");
}
catch(Exception e){
e.printStackTrace();
}
}
Fortunately found the solution myself. .First need to run flush() and close() method and then the second(named:-open) method. Inside open method, instead of R
Runtime.getRuntime().exec(cmd);
i expanded it into two lines:-
Runtime run = Runtime.getRuntime();
Run.exec(cmd);
Thats it..:D
I'm busy with a FileWriter, and with very limited knowledge of writing text files, I found a few examples of what I need, and with that I created my own coding. I'm working in NetBeans.
The Objective:
Export JTable contents to a text file on button pressed.
The Problem:
bw.write(model.getValueAt(i, j));
The pre-error show: No suitable method found for write(Output)...
What's going on here?
This is how the process works:
1)The administrator runs the First Run Configuration
2)The administrator clicks on Add User {1}
(Apps.Settings.FTRun)
3)The administrator creates the user by entering the fields. Clicking on insert, the app creates a userid, then uploads the user to the database. ALSO, it adds the username and password to the table in FTRun.It's supposed to add the elements, but it doesn't! (Code included below)
Apps.UserManager.AddUser
4)The table doesn't populate, so I type in random strings in the table. I then click on . This throws the NullPointerException
Here's my code:
1) Export Code
2) Populate Table Code
Export Code
try {
File file = new File("C:/Program Files/DocuLoc/bin/export.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
TableModel model = jTable1.getModel();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < model.getRowCount(); i++) {
for (int j = 0; j < model.getColumnCount(); j++) {
//Create your File Writer
bw.write(model.getValueAt(i, j));
}
}
bw.close();
JOptionPane.showConfirmDialog(this, "Table exported successfully!\nFile located at " + file);
} catch (Exception e) {
e.printStackTrace();
}
Populate Table Code
try {
Apps.Settings.FTRun ftrun = new Apps.Settings.FTRun();
DefaultTableModel model = (DefaultTableModel) ftrun.jTable1.getModel();
model.addRow(new Object[]{UploadUName, UploadPwd});
ftrun.jTable1.enableInputMethods(true);
} catch (Exception e) {
e.printStackTrace();
}
I would use:
bw.write( model.getValueAt(i, j).toString() );
which will write the String representation of any Object you might be storiung in your TableModel.
Edit:
The NPE is caused by the bw.write(model.getValueAt(i,j).toString()); line
So what is null, "bw", "model", the data from the getValue(...) method?
I'm guessing the data, in which cause you can use code like:
Object data = model.getValueAt(I, j);
if (data == null)
System.out.println("null data at - " + I + " : " + j);
else
bw.write( data.toString() );
then once you know what cell(s) are null you investigate to find out why.
None of BufferedWriter's write methods take an Object type as returned by getValueAt. You could do
bw.write((String)model.getValueAt(i, j));
Thanks to #camickr and #Reimeus for assistance in solving this!
This code shows how you write JTable contents to a text file.
If your table has values, your code should look like this:
try {
File file = new File(filePathAndFileName); //Format: C:/.../.../file.txt
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
//OPTIONAL: clear the file contents. Omitting this will continue
// writing the file
PrintWriter writer = new PrintWriter(file.getAbsoluteFile());
writer.print("");
writer.close();
//Start the writing process
TableModel model = jTable1.getModel();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
//Execute writer to write until all values in the table have been written
for (int i = 0; i < model.getRowCount(); i++) {
for (int j = 0; j < model.getColumnCount(); j++) {
Object data = model.getValueAt(i, j);
bw.write(data.toString());
}
}
//OPTIONAL - If you have multiple columns and want to separate, use the
// following instead of the execution above
//FORMAT Column1 : Column2 : ...
//new line Column1 : Column2 : ...
for (int i = 0; i < model.getRowCount(); i++) {
for (int j = 0; j < model.getColumnCount(); j++) {
Object data = model.getValueAt(i, j);
bw.write(data.toString());
//Custom coding here for the row. I used two columns
if (j == 0) {
bw.write(" : ");
} else {
}
}
bw.newLine();
}
//End the Writing Process
bw.close();
System.out.println("Writing complete");
}catch(Exception ex){
e.printStackTrace();
}
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.