Convert csv to xls/xlsx using Apache poi? - spring

I need to convert csv to xls/xlsx in my project? How can i do that? Can anyone post me some examples? I want to do it with Apache poi. I also need to create a cell from java side.

You can try following method to create xlsx file using apache-poi.
public static void csvToXLSX() {
try {
String csvFileAddress = "test.csv"; //csv file address
String xlsxFileAddress = "test.xlsx"; //xlsx file address
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheet = workBook.createSheet("sheet1");
String currentLine=null;
int RowNum=0;
BufferedReader br = new BufferedReader(new FileReader(csvFileAddress));
while ((currentLine = br.readLine()) != null) {
String str[] = currentLine.split(",");
RowNum++;
XSSFRow currentRow=sheet.createRow(RowNum);
for(int i=0;i<str.length;i++){
currentRow.createCell(i).setCellValue(str[i]);
}
}
FileOutputStream fileOutputStream = new FileOutputStream(xlsxFileAddress);
workBook.write(fileOutputStream);
fileOutputStream.close();
System.out.println("Done");
} catch (Exception ex) {
System.out.println(ex.getMessage()+"Exception in try");
}
}

We can use SXSSF Jar in which we can parse a long file as below:
public static void main( String[] args ) {
try {
// String fName = args[ 0 ];
String csvFileAddress = "C:\\Users\\psingh\\Desktop\\test\\New folder\\GenericDealerReport - version6.txt"; //csv file address
String xlsxFileAddress = "C:\\Users\\psingh\\Desktop\\trial\\test3.xlsx"; //xlsx file address
SXSSFWorkbook workBook = new SXSSFWorkbook( 1000 );
org.apache.poi.ss.usermodel.Sheet sheet = workBook.createSheet( "sheet1" );
String currentLine = null;
int RowNum = -1;
BufferedReader br = new BufferedReader( new FileReader( csvFileAddress ) );
while ( ( currentLine = br.readLine() ) != null ) {
String str[] = currentLine.split( "\\|" );
RowNum++;
Row currentRow = sheet.createRow( RowNum );
for ( int i = 0; i < str.length; i++ ) {
currentRow.createCell( i )
.setCellValue( str[ i ] );
}
}
DateFormat df = new SimpleDateFormat( "yyyy-mm-dd-HHmmss" );
Date today = Calendar.getInstance()
.getTime();
String reportDate = df.format( today );
FileOutputStream fileOutputStream = new FileOutputStream( xlsxFileAddress );
workBook.write( fileOutputStream );
fileOutputStream.close();
//System.out.println( "Done" );
}
catch ( Exception ex ) {
System.out.println( ex.getMessage() + "Exception in try" );
}
}

public static void convertCsvToXlsx(String xlsLocation, String csvLocation) throws Exception {
SXSSFWorkbook workbook = new SXSSFWorkbook();
SXSSFSheet sheet = workbook.createSheet("Sheet");
AtomicReference<Integer> row = new AtomicReference<>(0);
Files.readAllLines(Paths.get(csvLocation)).forEach(line -> {
Row currentRow = sheet.createRow(row.getAndSet(row.get() + 1));
String[] nextLine = line.split(",");
Stream.iterate(0, i -> i + 1).limit(nextLine.length).forEach(i -> {
currentRow.createCell(i).setCellValue(nextLine[i]);
});
});
FileOutputStream fos = new FileOutputStream(new File(xlsLocation));
workbook.write(fos);
fos.flush();
}

I have found SXSSFWorkbook really faster then XSSFWorkbook. Here is the modified code:
try {
String csvFileInput = "inputFile.csv";
String xlsxFileOutput ="outputFile.xls";
LOGGER.error(csvFileInput);
LOGGER.error( xlsxFileOutput);
SXSSFWorkbook workBook = new SXSSFWorkbook();
Sheet sheet = workBook.createSheet(transformBean.getOutputFileName());
String currentLine = null;
int RowNum = 0;
BufferedReader br = new BufferedReader(new FileReader(csvFileInput));
while ((currentLine = br.readLine()) != null) {
String str[] = currentLine.split(",");
RowNum++;
Row currentRow = sheet.createRow(RowNum);
for (int i = 0; i < str.length; i++) {
currentRow.createCell(i).setCellValue(str[i]);
}
}
FileOutputStream fileOutputStream = new FileOutputStream(xlsxFileOutput);
workBook.write(fileOutputStream);
fileOutputStream.close();
System.out.println("Done");
} catch (Exception ex) {
System.out.println(ex.getMessage() + "Found Exception");
}

if(new File(newFileName).isFile()) return;
#SuppressWarnings("resource")
HSSFWorkbook wb = new HSSFWorkbook();
Row xlsRow;
Cell xlsCell;
HSSFSheet sheet = wb.createSheet("sheet1");
int rowIndex = 0;
for(CSVRecord record : CSVFormat.EXCEL.parse(new FileReader(fileName))) {
xlsRow = sheet.createRow(rowIndex);
for(int i = 0; i < record.size(); i ++){
xlsCell = xlsRow.createCell(i);
xlsCell.setCellValue(record.get(i));
}
rowIndex ++;
}
FileOutputStream out = new FileOutputStream(newFileName);
wb.write(out);
out.close();

Try this one if you have inputstream
public static XSSFWorkbook csvToXLSX(InputStream inputStream) throws IOException {
XSSFWorkbook workBook = new XSSFWorkbook();
try(BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
Sheet sheet = workBook.createSheet("sheet1");
String currentLine=null;
int rowNum=0;
while ((currentLine = br.readLine()) != null) {
String[] str = currentLine.split(",");
rowNum++;
Row currentRow=sheet.createRow(rowNum);
for(int i=0;i<str.length;i++){
currentRow.createCell(i).setCellValue(str[i]);
}
}
log.info("CSV file converted to the workbook");
return workBook;
} catch (Exception ex) {
log.error("Exception while converting csv to xls {}",ex);
}finally {
if (Objects.nonNull(workBook)) {
workBook.close();
}
}
return workBook;
}

Related

Return a new thymeleaf page fragment and some file from spring controller

Tell me how to properly implement the spring controller. I want it to return a new thymeleafe page fragment and Excel file at the same time.
I know how to implement a controller to return a page fragment:
#GetMapping("/some_url")
public String updateFragment(Model model) {
model.addAttribute("attribute", someAtribute);
return "some_page :: fragment";
}
And I know how to implement a controller for downloading files:
#GetMapping("some_url")
public void getReport(HttpServletResponse response) throws IOException {
response.setContentType("application/octet-stream");
String headerKey = "Content-Disposition";
String headerValue = "attachment; filename=file.xlsx";
response.setHeader(headerKey, headerValue);
try {
FileInputStream inputStream = new FileInputStream(new File("path_to_file"));
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
int row = 12;
Row exampleRow = sheet.getRow(12);
int count = 1;
for (SIZForKomplex s : objectList) {
if (s.getNumber() != 0) {
sheet.getRow(row).setRowStyle(exampleRow.getRowStyle());
sheet.getRow(row).setHeight(exampleRow.getHeight());
for (int i = 0; i < 8; i++) {
sheet.getRow(row).getCell(i).setCellStyle(exampleRow.getCell(i).getCellStyle());
}
sheet.getRow(row).getCell(0).setCellValue(count);
sheet.getRow(row).getCell(1).setCellValue(s.getNomenclatureNumber());
sheet.getRow(row).getCell(2).setCellValue(s.getNamesiz());
sheet.getRow(row).getCell(3).setCellValue(s.getSize());
sheet.getRow(row).getCell(4).setCellValue(s.getHeight());
sheet.getRow(row).getCell(5).setCellValue(s.getNumber());
sheet.getRow(row).getCell(6).setCellValue(sizRepository.findById(s.getId()).orElseThrow().getEd_izm());
sheet.getRow(row).getCell(7).setCellValue(" ");
row++;
count++;
}
}
inputStream.close();
ServletOutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException | EncryptedDocumentException
ex) {
ex.printStackTrace();
}
}
But how do I combine this. I need to update the data on the page and download the Excel file

The specified string is not in the form required for an e-mail address.i am getting Emails from Database

this is method
#region StuDetailsMail
public List StuDetailsMail(string Stu_Name, string Stu_Email, string Stu_Mobile)
{
List data = new List();
SqlParameter[] sqlprm = new SqlParameter[3];
SqlDataReader dr = null;
try {
sqlprm[0] = new SqlParameter(DBProcedures.sqlparam_Name, Stu_Name);
sqlprm[1] = new SqlParameter(DBProcedures.sqlpram_Email, Stu_Email);
sqlprm[2] = new SqlParameter(DBProcedures.sqlpram_Mobile_Num, Stu_Mobile);
dr = objDAL.ExecuteReader(DBProcedures.Usp_StuEmail, ref sqlprm, false);
while (dr.Read())
{
InstEmails list1 = new InstEmails()
{
Emaillist = dr["email"].ToString(),
};
data.Add(list1);
};
foreach (var emailId in data)
{
string MessageBody = "studentname" + Stu_Name + " is Intersted" + "studentmail is" + Stu_Email;
string MailSubject = "this is from Traininghubs";
obj.SendEmailToInstitute(emailId.ToString(), MessageBody, MailSubject);
}
}
catch(Exception e)
{
}
return data;
}
#endregion

Receive assets on Handheld

I'm sending files from wear to handheld side. I'm sending 4 or 5 files (2 of them are bigger) but everytime the handheld side only receives ONE of the bigger ones...
wear:
public void sendFile(String filename){
//BLE files
fileToArray("BLEdata/" + filename + "_RightDevice.txt", "/BLEdata/");
//send log file
fileToArray(filename + "_LOG.txt", "/LOGdata/");
//send GPS file
fileToArray("GPSdata/" + filename + "_GPS.txt", "/GPSdata/");
//send Report files
fileToArray("Report/" + filename + "_Report.txt", "/REPORTdata/");
//BLE files
fileToArray("BLEdata/" + filename + "_LeftDevice.txt", "/BLEdata/");
}
public void fileToArray(String filename, String path)
{
FileInputStream fileInputStream = null;
File file = new File(Environment.getExternalStorageDirectory() + "/TuneWear/" + filename);
System.out.println("PATH: " + file.getPath());
if(file.exists()){
byte[] bFile = new byte[(int) file.length()];
try {
//convert file into array of bytes
fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
fileInputStream.close();
WearResultsActivity main = (WearResultsActivity) getActivity();
long time = main.getInitTime();
if(filename.contains("_RightDevice")){
new SendToDataLayerThread(path + time, bFile, 2).start();
}else if (filename.contains("_LeftDevice")){
new SendToDataLayerThread(path + time, bFile, 1).start();
} else
new SendToDataLayerThread(path + time, bFile).start();
}catch(Exception e){
e.printStackTrace();
}
} else System.out.println("Doesn't exist:\n" + file.getPath());
}
class SendToDataLayerThread extends Thread {
String path;
byte[] bFile;
int footSide;
// Constructor for sending data objects to the data layer
SendToDataLayerThread(String p, byte[] bytes, int footside) {
path = p;
bFile = bytes;
footSide = footside;
}
SendToDataLayerThread(String p, byte[] bytes) {
path = p;
bFile = bytes;
}
public void run() {
WearResultsActivity main = (WearResultsActivity) getActivity();
GoogleApiClient googleClient = main.getGoogleClient();
Asset asset = Asset.createFromBytes(bFile);
System.out.println(asset.toString());
PutDataMapRequest dataMap = PutDataMapRequest.create(path);
dataMap.getDataMap().putLong("timestamp", Calendar.getInstance().getTimeInMillis());
dataMap.getDataMap().putLong("/InitialTime", ((WearResultsActivity) getActivity()).getInitTime());
dataMap.getDataMap().putAsset("asset", asset);
if(footSide == 1) {
dataMap.getDataMap().putInt("footside", footSide);
System.out.println("DATAMAP COM LEFT " + footSide);
}else if (footSide == 2) {
dataMap.getDataMap().putInt("footside", footSide);
System.out.println("DATAMAP COM RIGHT " + footSide);
}
PutDataRequest request = dataMap.asPutDataRequest();
PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi.putDataItem(googleClient, request);
pendingResult.setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
#Override
public void onResult(DataApi.DataItemResult dataItemResult) {
System.out.println("RESULT");
}
});
//Wearable.DataApi.putDataItem(googleClient, request);
}
}
Handheld:
#Override
public void onDataChanged(DataEventBuffer dataEvents) {
System.out.println("COUNT " + dataEvents.getCount());
for (DataEvent event : dataEvents) {
DataItem item = event.getDataItem();
if (event.getType() == DataEvent.TYPE_CHANGED) {
// DataItem changed
if (item.getUri().getPath().contains(LOGdata)) {
final DataMapItem dataMapItem = DataMapItem.fromDataItem(item);
Asset asset = dataMapItem.getDataMap().getAsset("asset");
//TODO here
Wearable.DataApi.getFdForAsset(googleClient, asset).setResultCallback(
new ResultCallback<DataApi.GetFdForAssetResult>() {
#Override
public void onResult(DataApi.GetFdForAssetResult getFdForAssetResult) {
InputStream assetInputStream = getFdForAssetResult.getInputStream();
long initialTime = dataMapItem.getDataMap().getLong(KEY_INITIALTIME);
String fileName = new SimpleDateFormat("HH'h'mm'm'ss's'_dd-MM-yyyy").format(initialTime);
String dataPath = Environment.getExternalStorageDirectory().toString() + "/TuneWear/";
File myDir = new File(dataPath);
myDir.mkdirs();
File file = new File(myDir, "Run_" + fileName + "_LOG.txt");
System.out.println("FILE: " + file.getPath());
try {
FileOutputStream fOut = new FileOutputStream(file);
int nRead;
byte[] data = new byte[16384];
while ((nRead = assetInputStream.read(data, 0, data.length)) != -1) {
fOut.write(data, 0, nRead);
}
fOut.flush();
fOut.close();
} catch (IOException e) {
System.out.println("ERROR File write failed: " + e.toString());
}
}
}
);
} else if (item.getUri().getPath().contains(GPSdata)) {
final DataMapItem dataMapItem = DataMapItem.fromDataItem(item);
Asset asset = dataMapItem.getDataMap().getAsset("asset");
//TODO here
Wearable.DataApi.getFdForAsset(googleClient, asset).setResultCallback(
new ResultCallback<DataApi.GetFdForAssetResult>() {
#Override
public void onResult(DataApi.GetFdForAssetResult getFdForAssetResult) {
InputStream assetInputStream = getFdForAssetResult.getInputStream();
long initialTime = dataMapItem.getDataMap().getLong(KEY_INITIALTIME);
String fileName = new SimpleDateFormat("HH'h'mm'm'ss's'_dd-MM-yyyy").format(initialTime);
String dataPath = Environment.getExternalStorageDirectory().toString() + "/TuneWear/GPSdata/";
File myDir = new File(dataPath);
myDir.mkdirs();
File file = new File(myDir, "Run_" + fileName + "_GPS.txt");
System.out.println("FILE: " + file.getPath());
try {
FileOutputStream fOut = new FileOutputStream(file);
int nRead;
byte[] data = new byte[16384];
while ((nRead = assetInputStream.read(data, 0, data.length)) != -1) {
fOut.write(data, 0, nRead);
}
fOut.flush();
fOut.close();
} catch (IOException e) {
System.out.println("ERROR File write failed: " + e.toString());
}
}
}
);
} else if (item.getUri().getPath().contains(REPORTdata)) {
final DataMapItem dataMapItem = DataMapItem.fromDataItem(item);
Asset asset = dataMapItem.getDataMap().getAsset("asset");
//TODO here
Wearable.DataApi.getFdForAsset(googleClient, asset).setResultCallback(
new ResultCallback<DataApi.GetFdForAssetResult>() {
#Override
public void onResult(DataApi.GetFdForAssetResult getFdForAssetResult) {
InputStream assetInputStream = getFdForAssetResult.getInputStream();
long initialTime = dataMapItem.getDataMap().getLong(KEY_INITIALTIME);
String fileName = new SimpleDateFormat("HH'h'mm'm'ss's'_dd-MM-yyyy").format(initialTime);
String dataPath = Environment.getExternalStorageDirectory().toString() + "/TuneWear/Report/";
File myDir = new File(dataPath);
myDir.mkdirs();
File file = new File(myDir, "Run_" + fileName + "_Report.txt");
System.out.println("FILE: " + file.getPath());
try {
FileOutputStream fOut = new FileOutputStream(file);
int nRead;
byte[] data = new byte[16384];
while ((nRead = assetInputStream.read(data, 0, data.length)) != -1) {
fOut.write(data, 0, nRead);
}
fOut.flush();
fOut.close();
} catch (IOException e) {
System.out.println("ERROR File write failed: " + e.toString());
}
}
}
);
} else if (item.getUri().getPath().contains(BLEdata)) {
final DataMapItem dataMapItem = DataMapItem.fromDataItem(item);
Asset asset = dataMapItem.getDataMap().getAsset("asset");
//TODO here
Wearable.DataApi.getFdForAsset(googleClient, asset).setResultCallback(
new ResultCallback<DataApi.GetFdForAssetResult>() {
#Override
public void onResult(DataApi.GetFdForAssetResult getFdForAssetResult) {
InputStream assetInputStream = getFdForAssetResult.getInputStream();
long initialTime = dataMapItem.getDataMap().getLong(KEY_INITIALTIME);
String fileName = new SimpleDateFormat("HH'h'mm'm'ss's'_dd-MM-yyyy").format(initialTime);
String dataPath = Environment.getExternalStorageDirectory().toString() + "/TuneWear/BLEdata/";
File myDir = new File(dataPath);
myDir.mkdirs();
File file = null;
System.out.println("FOOT SIIIIIIDE: " + dataMapItem.getDataMap().getInt("footside"));
if(dataMapItem.getDataMap().getInt("footside") == 1){
file = new File(myDir, "Run_" + fileName + "_LeftDevice.txt");
System.out.println("FILE: " + file.getPath());
} else if(dataMapItem.getDataMap().getInt("footside") == 2){
file = new File(myDir, "Run_" + fileName + "_RightDevice.txt");
System.out.println("FILE: " + file.getPath());
}
try {
FileOutputStream fOut = new FileOutputStream(file);
int nRead;
byte[] data = new byte[16384];
while ((nRead = assetInputStream.read(data, 0, data.length)) != -1) {
fOut.write(data, 0, nRead);
}
fOut.flush();
fOut.close();
}
catch (IOException e) {
System.out.println("ERROR File write failed: " + e.toString());
}
}
}
);
}
} else if (event.getType() == DataEvent.TYPE_DELETED) {
// DataItem deleted
System.out.println("DataItem deleted: " + event.getDataItem().getUri());
}
//Wearable.DataApi.deleteDataItems(googleClient, event.getDataItem().getUri(), DataApi.FILTER_PREFIX);
}
}
I only receive the GPS, Report and LOG data every time. The other 2 files I only receive ONE... Im sending them exactly the same way, but I'm receiving only one of them.
Does anyone detects the error on my code???
EDIT
I just discovered that if the smartwatch is connected to the handheld at the time that the files are sent, they are all received. If they are not connected, one of the files (RightDevice.txt or LeftDevice.txt) are not received when they connect...
I solved it!
It was the most basic error of all.... I was sending the same path for the two files (RightDevice and LeftDevice) so only one of the objects was updated on the googleapiclient.

File is getting locked on read/write operation in C#

A third party application is reading the output text file of my windows application,it is getting paused.I think,it is happening because of file gets locked either on writing or reading.how can i make this work fine.Please see my code.
List<string> fileList = new List<string>();
System.Timers.Timer timer;
string currentfilename;
string currentcontent;
public Service1()
{
//
timer = new System.Timers.Timer();
timer.AutoReset = false;
timer.Elapsed += new System.Timers.ElapsedEventHandler(DoStuff);
}
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
throw new NotImplementedException();
}
private void DoStuff(object sender, System.Timers.ElapsedEventArgs e)
{
DateTime LastChecked = DateTime.Now;
try
{
string[] files = System.IO.Directory.GetFiles(#"C:\Journal", "*.jrn", System.IO.SearchOption.AllDirectories);
foreach (string file in files)
{
if (!fileList.Contains(file))
{
currentfilename = file;
fileList.Add(file);
copywarehouse(file);
try
{
string sourcePath = #"C:\Journal";
string sourceFile = System.IO.Path.Combine(sourcePath, file);
using (FileStream fs= new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
StreamReader sr = new StreamReader(fs);
currentcontent = sr.ReadToEnd();
sr.Close();
}
}
catch (Exception ex)
{
throw (ex);
}
}
}
try
{
string sourcePath1 = #"C:\Journal";
string currentfilecontent;
string sourceFile1 = System.IO.Path.Combine(sourcePath1, currentfilename);
using (FileStream fs = new FileStream(sourceFile1, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
StreamReader sr = new StreamReader(fs);
currentfilecontent = sr.ReadToEnd();
sr.Close();
}
if (currentfilecontent != currentcontent)
{
if (currentfilecontent.Contains(currentcontent))
{
string originalcontent = currentfilecontent.Substring(currentcontent.Length);
File.WriteAllText(#"C:\Journal\tempfile.txt", originalcontent + "\r\n");
using (FileStream fs = new FileStream(#"C:\Journal\tempfile.txt", FileMode.OpenOrCreate))
{
StreamWriter sw = new StreamWriter(fs);
sw.Write(originalcontent);
sw.Close();
}
currentcontent = currentfilecontent;
}
}
}
//}
catch (Exception ex)
{
throw (ex);
}
TimeSpan ts = DateTime.Now.Subtract(LastChecked);
TimeSpan MaxWaitTime = TimeSpan.FromMilliseconds(100);
if (MaxWaitTime.Subtract(ts).CompareTo(TimeSpan.Zero) > -1)
timer.Interval = MaxWaitTime.Subtract(ts).Milliseconds;
else
timer.Interval = 1;
timer.Start();
}
catch (Exception ex)
{
throw (ex);
}
}
private void copywarehouse(string filename)
{
string sourcePath = #"C:\Journal";
string targetPath = #"C:\Journal";
string copycontent=null;
try
{
string sourceFile = System.IO.Path.Combine(sourcePath, filename);
string destFile = System.IO.Path.Combine(targetPath, "tempfile.txt");
using (FileStream fs = new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
StreamReader sr = new StreamReader(fs);
copycontent = sr.ReadToEnd();
sr.Close();
}
using (FileStream fs = new FileStream(destFile, FileMode.Append))
{
StreamWriter sw = new StreamWriter(fs);
sw.Write(copycontent);
sw.Close();
}
}
catch (Exception ex)
{
throw (ex);
}
}
Here the problem is with third party application which is reading my application output as input.it is not allowing access to more than one file content..

Trouble with download jpeg image

I need to download jpeg image and show it in my midlet.
But when I try to run this code, image on screen is broken.
What is wrong?
public void startApp() {
HttpConnection conn = null;
InputStream is = null;
try {
conn = (HttpConnection) Connector.open("http://av.li.ru/227/2374227_8677578.jpg", Connector.READ, false);
conn.setRequestMethod( HttpConnection.GET);
int rc = conn.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new Exception("ResponseCode = " + rc);
}
is = conn.openDataInputStream();
byte []b = new byte[(int) conn.getLength()];
is.read(b);
Image img = Image.createImage(b, 0, b.length);
Form f = new Form("test");
f.append(img);
Display.getDisplay(this).setCurrent(f);
} catch (Exception e) {
}
}
Thanks

Resources