I stored data from the database to ArrayList.and I get that data from ArrayList to write on excel file for users download purpose. when I write to excel file, it will write perfectly.but when I write more data the last line called "total" come inside the other lines.coding as below.
public String excel_missedcall(List<datefilter> result1){
Date date = new Date(System.currentTimeMillis());
String download_file="";
Properties prop = new Properties();
InputStream input = null;
String link="";
String linkfilepath="";
//read file name from properties file
try {
String filename = "config.properties";
input = MainController.class.getClassLoader().getResourceAsStream(
filename);
if (input == null) {
System.out.println("Sorry, unable to find " + filename);
}
// load a properties file from class path, inside static method
prop.load(input);
String filepath=prop.getProperty("missedcall_filePath");
download_file=filepath+"missedcall_"+date.getTime()+".xlsx";
link=prop.getProperty("missedcall_downloadfilePath");
linkfilepath=link+"missedcall_"+date.getTime()+".xlsx";
int total=0;
//create excel sheet
//Blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank sheet
XSSFSheet sheet= workbook.createSheet("Missedcall");
//This data needs to be written (Object[])
Map<String, Object[]> data = new TreeMap<String, Object[]>();
data.put("1", new Object[] {"Date", "TotalCalls"});
for(int i=0;i<result1.size();i++){
data.put(""+(i+2),new Object[] {result1.get(i).getMisscall_date(),Integer.parseInt(result1.get(i).getSum_misscall())});
total+=Integer.parseInt( result1.get(i).getSum_misscall());
//System.out.println("**********1*********"+(i+2));
}
data.put(""+(result1.size()+2), new Object[] {"Total", total});
//Iterate over data and write to sheet
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset)
{
System.out.println("*********1**********"+key);
Row row = sheet.createRow(rownum++);
System.out.println("*********2**********"+rownum);
Object [] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr)
{
Cell cell = row.createCell(cellnum++);
if(obj instanceof String)
cell.setCellValue((String)obj);
else if(obj instanceof Integer)
cell.setCellValue((Integer)obj);
}
}
try
{
//Write the workbook in file system
FileOutputStream out1 = new FileOutputStream(new File(download_file));
workbook.write(out1);
out1.close();
System.out.println("xlsx written successfully on disk.");
}
catch (Exception e)
{
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return linkfilepath;
}
Output of excel file is:
Date TotalCalls
2015-08-28 1895
2015-08-29 599
2015-08-30 354
2015-08-31 2028
Total 6712
2015-08-20 0
2015-08-21 0
2015-08-22 2
2015-08-23 12
2015-08-24 22
2015-08-25 324
2015-08-26 878
2015-08-27 598
Please help me.
You are using String as key , replace following line
Map<String, Object[]> data = new TreeMap<String, Object[]>();
with
Map<Integer, Object[]> data = new TreeMap<Integer, Object[]>();
Related
I have a very simple .csv file with ID's and serial numbers
the actual application will not know how many rows but will always have two columns
1,16600687
2,16600939
3,16604031
4,16607302
I have everything else setup but i am only loading the data into a 1D array and the comma is remaining in the data
The result i get is string value for 3rd position is 3,16604031
How do i separate this so it is a 2D array with get value [2,0] is 3 and get value [2,1] is 16604031 ?
private void button1_Click(object sender, EventArgs e)
{
string stFileNamenPath = "(put location of file here)";
DialogResult result = openFileDialog1.ShowDialog();
StreamReader sr = new StreamReader(stFileNamenPath);
string[] sortArray = null;
while (!sr.EndOfStream)
{
string strResult = sr.ReadToEnd();
sortArray = strResult.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
}
string stTest = (string)sortArray.GetValue(2);
MessageBox.Show("string value for 3rd position is " + stTest);
}
CSV file
1,16600687
2,16600939
3,16604031
4,16607302
The answer that comes to my mind is just a LINQ Where statement followed by a Select statement. The former for filtering and the second for actually remaping the data you have. You code would be something like this
string stFileNamenPath = "(put location of file here)";
//DialogResult result = openFileDialog1.ShowDialog();
StreamReader sr = new StreamReader(stFileNamenPath);
string[] sortArray = null;
while (!sr.EndOfStream)
{
string strResult = sr.ReadToEnd();
sortArray = strResult.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
}
char separator = ',';
var mappedArray = sortArray
.Where(x => !string.IsNullOrEmpty(x) && !string.IsNullOrWhiteSpace(x))
.Select(x => new string[] { x.Split(separator)[0], x.Split(separator)[1] }).ToArray();
var stTest = mappedArray[2][1];
MessageBox.Show("string value for 3rd position is " + stTest);
I am trying to convert a large xlsx sheet to csv using the example given here and here . But it is throwing the below error on line
XSSFWorkbook wBook = new XSSFWorkbook(new FileInputStream(file));
Error
Caught throwable Java heap space
java.lang.OutOfMemoryError: Java heap space
at java.io.ByteArrayOutputStream.<init>(ByteArrayOutputStream.java:77)
Is there any efficient way to convert large xlsx sheet to csv without increasing heap memory?
My code is as below-
try
{
// Get the workbook object for XLSX file
// XSSFWorkbook wBook = new XSSFWorkbook(new FileInputStream(file));
XSSFWorkbook wBook = new XSSFWorkbook(new FileInputStream(file));
for(int i=0;i<wBook.getNumberOfSheets();i++)
{
XSSFSheet sheet = wBook.getSheetAt(i);
fileName = convertedFileLocation + sheet.getSheetName() + ".csv";
FileOutputStream fos = new FileOutputStream(fileName);
//System.out.println(wBook.getSheetAt(i).getSheetName());
Row row;
Cell cell;
// Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
row = rowIterator.next();
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
cell = cellIterator.next();
data.append("\"" + cell.getStringCellValue() + "\",\r\n");
}
}
fos.write(data.toString().getBytes());
fos.close();
}
wBook.close();
}
Edited---
I am using XSSF as suggested by #axel and #gagravarr in the comment and using the class method as below. Though it is creating the converted.csv file the csv file is empty. Any idea what I am doing wrong
private boolean convertToCSV2(File file)
{
try {
OPCPackage p = OPCPackage.open(file.getPath());
String convertedFileLocation = siteConfigService.getProperty(CONVERTEDFOLDER);
String convertedFileName = convertedFileLocation+"converted.csv";
PrintStream pout=new PrintStream(convertedFileName);
XLSX2CSV xlsToCSV = new XLSX2CSV(p, pout, -1);
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
I'm working on a Windows Phone 8 app.
I'm having issue appending to my JSON file.
It works fine if I keep the app open but once I close it and come back in it starts back writing from the beginning of the file.
Relevant code:
private async void btnSave_Click(object sender, RoutedEventArgs e)
{
// Create a entry and intialize some values from textbox...
GasInfoEntries _entry = null;
_entry = new GasInfoEntries();
_entry.Gallons = TxtBoxGas.Text;
_entry.Price = TxtBoxPrice.Text;
_GasList.Add(_entry);
//TxtBlockPricePerGallon.Text = (double.Parse(TxtBoxGas.Text) / double.Parse(TxtBoxPrice.Text)).ToString();
// Serialize our Product class into a string
string jsonContents = JsonConvert.SerializeObject(_GasList);
// Get the app data folder and create or open the file we are storing the JSON in.
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile textfile = await localFolder.CreateFileAsync("gasinfo.json", CreationCollisionOption.OpenIfExists); //if get await operator error add async to class (btnsave)
//open file
using (IRandomAccessStream textstream = await textfile.OpenAsync(FileAccessMode.ReadWrite))
{
//write JSON string
using (DataWriter textwriter = new DataWriter(textstream))
//using (DataWriter textwriter = new DataWriter(textstream))
{
textwriter.WriteString(jsonContents);
await textwriter.StoreAsync(); //writes buffer to store
}
}
}
private async void btnShow_Click(object sender, RoutedEventArgs e)
{
StorageFolder localfolder = ApplicationData.Current.LocalFolder;
try
{
// Getting JSON from file if it exists, or file not found exception if it does not
StorageFile textfile = await localfolder.GetFileAsync("gasinfo.json");
using (IRandomAccessStream textstream = await textfile.OpenReadAsync())
{
//read text stream
using (DataReader textreader = new DataReader(textstream))
{
//get size ...not sure what for think check the file size (lenght) then based on next 2 commands waits until its all read
uint textlength = (uint)textstream.Size;
await textreader.LoadAsync(textlength);
//read it
string jsonContents = textreader.ReadString(textlength);
// deserialize back to gas info
_GasList = JsonConvert.DeserializeObject<List<GasInfoEntries>>(jsonContents) as List<GasInfoEntries>;
displayGasInfoEntries();
}
}
}
catch
{
txtShow.Text = "something went wrong";
}
}
private void displayGasInfoEntries()
{
txtShow.Text = "";
StringBuilder GasString = new StringBuilder();
foreach (GasInfoEntries _entry in _GasList)
{
GasString.AppendFormat("Gallons: {0} \r\n Price: ${1} \r\n", _entry.Gallons, _entry.Price); // i think /r/n means Return and New line...{0} and {1} calls "variables" in json file
}
txtShow.Text = GasString.ToString();
}
Thanks
Do you call the btnShow_Click each time you've started the app? Because otherwise the _GasList will be empty; if you now call the btnSave_Click all previous made changes will be lost.
So please make sure, that you restore the previously saved json data before you add items to the _GasList.
/*the below code is i am trying for the notification of new mail i am trying to fetch the prestored value into the file and compare it to the new value from the method
public static void main(String args[]) throws MessagingException{
try {
Notification n= new Notification();
int a =n.Notification();
BufferedReader br = null;
//read from the earlier file value of the total messages
String sCurrentLine;
br = new BufferedReader(new FileReader("Notification.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
int b = Integer.parseInt(sCurrentLine);
if (a>b){
System.out.println("you have "+(a-b)+" new Messsages");
}else{
System.out.println("NO New message");
}
//write the new value of the total messages to the file
Writer output = null;
File file = new File("Notification.txt");
output = new BufferedWriter(new FileWriter(file, true));
output.write(String.valueOf(a));
output.close();
} catch (IOException ex) {
Logger.getLogger(Notification.class.getName()).log(Level.SEVERE, null, ex);
}
}
If the file you are reading from only contains a number that you require, maybe this is what you have to do:
if ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
int b = Integer.parseInt(sCurrentLine);
// do other stuff
}
else
{
// file empty
}
How to export JTable java swing /jidesoft cell background colors to excel .xls file?
if you want to export string value into csv file (excel support it), or you can use other library for example Apache POI.
public static void exportJTable (JTable table, String fileName) throws Exception {
StringBuilder content = new StringBuilder("");
for (int i=0; i<table.getModel().getRowCount(); i++){
for (int j=0; j<table.getModel().getColumnCount(); j++) {
int col = table.convertColumnIndexToView(j);
String value = null ;
try {
value = (String) table.getModel().getValueAt(i, col);
}
catch (java.lang.ClassCastException e) {
}
if ( value == null)
value = "" ;
// CSV file
value.replaceAll(",", "");
content.append(value + ",");
}
content.append("\n");
}
writeToFile(content.toString(),fileName);
}
private static void writeToFile (String data, String fileName) throws FileNotFoundException, UnsupportedEncodingException {
File file = new File(fileName);
PrintWriter writer = new PrintWriter(file,"UTF-8");
writer.println(data);
writer.close();
}