I have a java class using csv writer which creates csv file.As know everything will be in text format,I want a specific column data to be a hyperlink.For example consider a table with 1 rows and 4 columns
OUTPUT is : when opened in excel .Each entry will be in a new cell
Col1 Col2 Col3 Col4
OUTPUT when opened in Open Office
Col1,Col2,Col3,Col4
The above data is when I open my csv file in excel.This creation is done by my csv writer in java.
What I wanted here is that Col3 should be a hyperlink
Below is my code
public String[] convertEntry(Info ItemInfo) {
String[] columns = new String[NUMBER_OF_COLUMNS];
columns[1] = "Col1;
columns[2] = "Col2";
columns[3] = "Col3";
columns[4] = "Col4";
return columns;
}
Hope am clear.Any help is appreciated
It's ugly but:
this,is,a,=HYPERLINK("http://www.google.com"),test,csv
Will automatically create it. Otherwise you can turn on the configuration for autocompletion in Excel so they always change. But CSV is supposed to be text, I would suggest leaving it as just the URL and having the user know what they are doing to change it.
EDIT:
public String[] convertEntry(Info ItemInfo) {
String[] columns = new String[NUMBER_OF_COLUMNS];
columns[1] = "Col1;
columns[2] = "Col2";
columns[3] = "=HYPERLINK(" + ItemInfo.Col3 + ")";
columns[4] = "Col4";
return columns;
}
Just wrap the value in the =HYPERLINK() function and it will automatically be a link in excel.
Related
I am unable to get the comma separated values from the excel cell using java code.
I had tried using the following code also.
String [] items = commaSeparated.split("\\s*,\\s*");
List<String> container = Arrays.asList(items);
I want the output as a list like:
IND
PAK
USA
AUS
When the input is imported from the Excel cell as IND,PAK,USA,AUS.
If all you want to do is print each item of your CSV data on a new line, this code will do the job.
String csvLine = "IND,PAK,USA,AUS";
Arrays.stream(csvLine.split(",")).forEach(
item -> System.out.println(item)
);
i have excel file (.xlsx) with column
Column1 Column2 Column3 Column1
A 50 30 40
B 45 40 20
.......................................
I need to import this excel in MySQL database. I use following code:
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream(new File("Data.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook (fis);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator ite = sheet.rowIterator();
while(ite.hasNext()){
Row row = (Row) ite.next();
Iterator<Cell> cite = row.cellIterator();
while(cite.hasNext()){
Cell c = cite.next();
System.out.print(c.toString() +";");
}
System.out.println();
}
fis.close();
}
I need to get in list all row. This code show in console all data from row, but I don't now to add that data in list and list import to MySQL.
Any idea?
I can think of few approaches in order to write this data into the MySQL database but, I will give you the most basic approach to achieve what you desire. You are using Apache POI library in order to log all the data to console.
while (rows.hasNext()) {
String[] rowsVal = new String[Number_of_Columns];
if (row.getCell(0).getStringCellValue().equalsIgnoreCase("Column_Name")) {
row = rows.next();
}
while (cells.hasNext()) {
keyVal[j] = cells.next().getStringCellValue();
j++;
}
}
Above code will store the content of the first row in the keyVal[] array.
Now, you need to include the packages containing the JDBC classes needed for database programming. Following code snippet will be useful to insert records into the table:
String sql = "INSERT INTO Table " + "VALUES ("keyVal[0] + "," + keyVal[1] + "," + keyVal[2] + "," + keyVal[3])";
The above code snippet will help you in inserting the data into the database.
Links for Reference:
https://www.tutorialspoint.com/jdbc/jdbc-insert-records.htm
This is not a direct answer to your question, but may in fact be an even better approach than what you are considering. You may try exporting your Excel worksheet as a CSV file. This means the lines would look like:
Column1,Column2,Column3,Column4
A,50,30,40
With this CSV file in hand, you may then use MySQL's LOAD DATA tool, which allows for rapidly importing CSV or other regular data:
LOAD DATA INFILE 'C:/path/to/Data.xlsx'
INTO TABLE yourTable
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS;
The motivation for possibly avoiding your current approach is that it is costly to use an Apache library to open an Excel workbook, and then read it. Even after doing this, you still would need to use JDBC to write that data to MySQL.
I have recently tried to code a small java file which will insert a row into an already existing table in a .odt document. The table itself has 4 rows and 3 column, but I would like to implement a check which will expand that table if the content to be inserted is larger than 4. However, every time I try to get the table's rows, it returns a null pointer. I am not that familiar with UNO api, but as far as i read through the documentation, the class XColumnsAndRowRange should be used in this situation. My code is as follows:
XTextTablesSupplier xTablesSupplier = (XTextTablesSupplier) UnoRuntime.queryInterface(XTextTablesSupplier.class, xTextDocument);
XNameAccess xNamedTables = xTablesSupplier.getTextTables();
try {
Object table = xNamedTables.getByName(tblName);
XTextTable xTable = (XTextTable) UnoRuntime.queryInterface(XTextTable.class, table);
XCellRange xCellRange = (XCellRange) UnoRuntime.queryInterface(XCellRange.class, table);
if(flag){
XColumnRowRange xCollumnAndRowRange =(XColumnRowRange)
UnoRuntime.queryInterface(XColumnRowRange.class, xCellRange);
XTableRows rows = xCollumnAndRowRange.getRows();
System.out.println("Testing if this works");
rows.insertByIndex(4, size-4);
}
I am not sure if I am missing something here or if I should be using a different function.
As Lyrl suggested, this works:
XTableRows rows = xTable.getRows();
Apparently XColumnRowRange is only used for spreadsheets.
Note: With Basic or Python you would not have this problem, because those languages do not need queryInterface. The code would simply be:
table = tables.getByName(tblName)
rows = table.getRows()
I am using Apache POI library to read/write to xlsx. In my original xlsx, I have a namedrange "XYZ".
I want to update the values of cells within this name range. How can I do that?
I did this:
XSSFName name = workbook.getName("XYZ");
String formula = name.getRefersToFormula();
System.out.println("Formula = " + formula);
Now, I dont know how to get a handle to individual cell in this named range.
Can anyone please point me to the correct API that I can use?
Rgds
Sapan
There is an example from the Busy Developers' Guide for retrieving the cells in the range. Then you can use Cell.setCellValue() to update.
// setup code
String cname = "TestName";
Workbook wb = getMyWorkbook(); // retrieve workbook
// retrieve the named range
int namedCellIdx = wb.getNameIndex(cname);
Name aNamedCell = wb.getNameAt(namedCellIdx);
// retrieve the cell at the named range and test its contents
AreaReference aref = new AreaReference(aNamedCell.getRefersToFormula());
CellReference[] crefs = aref.getAllReferencedCells();
for (int i=0; i<crefs.length; i++) {
Sheet s = wb.getSheet(crefs[i].getSheetName());
Row r = s.getRow(crefs[i].getRow());
Cell c = r.getCell(crefs[i].getCol());
// extract the cell contents based on cell type etc.
}
I have a Java class to automate some behaviour on the web, my only problem is that now instead of the static data that I have I need to use the data from the csv.
for example:
this is one of the actions in my automation class:
WebElement supplierAddressField = driver.findElement(By.id("FieldaddressOfSupplierLine"));
supplierAddressField.sendKeys("hollywood blvd 34");
So now, instead of the static "supplier address" value I want to iterate on each line of the .sendKeys(csvLineMap.get("supplier address"));
Because in each line I dont need all the headers info, this is why I think it will be the best to just create a list of maps, that each map key will be the header of the csv and the value will be the value for this header in a specific line.
this is the structure of the csv:
Please help me to figure this out...thanksss!!
Apache Commons CSV
For what you are asking for I would recommend you look at Apache Commons CSV. One of the examples from their User Guide matches very closely with with the examples you are trying
Reader in = new FileReader("path/to/file.csv");
Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
for (CSVRecord record : records) {
String lastName = record.get("Last Name");
String firstName = record.get("First Name");
}
ok, this might be overly complex for what you want, but I always open csv's as excel files because then you can run down the columns. The code for picking up any column would look like this:
Workbook w = Workbook.getWorkbook(inputWorkbook);
Sheet sheet = w.getSheet(0);
nom = sheet.getRows();
String[][] SheetArray = new String [2][nom];
// change the first number to the number of columns you want,
// or pick up the number same as you did with rows
Cell cell;
// GETS DATA FROM SHEET AND RUNS THROUGH WHOLE LOOP BELOW FOR EACH REFERENCE
for(int j =0;j<sheet.getRows();j++) // cycles through rows and loads into 2d array
{ // start 6
cell = sheet.getCell(0, j); <- your column number here
cellcont = cell.getContents();
SheetArray[0][j] = cellcont;
// repeat the above block for each column you want
} // end 6
you now have a 2d array with all the info in it which you can handle however you want.
wrap the entire thing in a try .. catch.
With uniVocity-parsers you can parse only the fields you are interested, in any order:
CsvParserSettings parserSettings = new CsvParserSettings();
// Let's extract headers
parserSettings.setHeaderExtractionEnabled(true);
parserSettings.selectFields("Field 5", "Field 1");
//Rows will come organized according to your field selection
List<String[]> allRows = parser.parseAll("path/to/file.csv");
If you prefer, you can easily get a map with the values of all columns:
CsvParserSettings parserSettings = new CsvParserSettings();
// Let's extract headers
parserSettings.setHeaderExtractionEnabled(true);
// To get the values of all columns, use a column processor
ColumnProcessor rowProcessor = new ColumnProcessor();
parserSettings.setRowProcessor(rowProcessor);
CsvParser parser = new CsvParser(parserSettings);
//This will kick in our column processor
parser.parse(new FileReader("path/to/file.csv"));
//Finally, we can get the column values:
Map<String, List<String>> columnValues = rowProcessor.getColumnValuesAsMapOfNames();
Have a look. It is faster than any other parser and you can do much more, such as converting the values and generating java beans.
Disclosure: I am the author of this library. It's open-source and free (Apache V2.0 license).