Does anyone have a sample app or some sample code to generate a CSV file on iOS?
Here is a simple code to generate CSV file :
NSArray *csvArray = [myTextView.text componentsSeparatedByString:#"\n"];
NSString *csvString = [csvArray componentsJoinedByString:#","];
NSLog(#"csvString:%#",csvString);
// Create .csv file and save in Documents Directory.
//create instance of NSFileManager
NSFileManager *fileManager = [NSFileManager defaultManager];
//create an array and store result of our search for the documents directory in it
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//create NSString object, that holds our exact path to the documents directory
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(#"Document Dir: %#",documentsDirectory);
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.csv", #"userdata"]]; //add our file to the path
[fileManager createFileAtPath:fullPath contents:[csvString dataUsingEncoding:NSUTF8StringEncoding] attributes:nil]; //finally save the path (file)
Following code I used for generating CSV.
NSMutableString *mainString=[[NSMutableString alloc]initWithString:#""];
for(int i=0;i<[commentArray count];i++ ) {
NSString *string=[[commentArray objectAtIndex:i]objectForKey:#"cmtName"];
string=[string stringByReplacingOccurrencesOfString:#"\"" withString:#"\"\""];
[mainString appendFormat:#"\"%#\"",string];
string=[[commentArray objectAtIndex:i]objectForKey:#"cmtDesc"];
string=[string stringByReplacingOccurrencesOfString:#"\"" withString:#"\"\""];
[mainString appendFormat:#",\"%#\"",string];
string=[[commentArray objectAtIndex:i]objectForKey:#"cmtType"];
string=[string stringByReplacingOccurrencesOfString:#"\"" withString:#"\"\""];
[mainString appendFormat:#",\"%#\"",string];
[mainString appendFormat:#",\"%#\"",string];
[mainString appendFormat:#"\n"];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectoryPath stringByAppendingPathComponent:#"Docment.conf"];
NSData* settingsData;
settingsData = [mainString dataUsingEncoding: NSASCIIStringEncoding];
if ([settingsData writeToFile:filePath atomically:YES])
NSLog(#"writeok");
And for importing CSV you use this
https://github.com/davedelong/CHCSVParser
My CHCSVParser will both read and write CSV files on OS X and iOS. It comes with some examples of how to use it.
Related
I am saving my files in Document directory named 1.png, 2.png, 3.png, 4.png, 5.png. If I delete the original file 3.png, how do I rename files 4.png and 5.png to be called 3.png and 4.png respectively?
This is the code I am using to write the files in the first place:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[appDel.photo addObject:#"photo"];
NSString *imageName = [NSString stringWithFormat:#"%i.png", [appDel.photo count]];
appDel.numberPhoto = [appDel.photo count];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
imageName];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
To get NSDocuments directory use :
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"MyFile.txt"];
How to rename file you can find here:
How to rename a file using NSFileManager
If you do not know the names of the files in documents directory you can use :
NSArray *directoryContent = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil];
This array contains all filenames you need. So you can rename them all.
in my application, i have placed an empty
myFile.txt
when i have internet connection , i get json data from internet and save the json string in it with following code
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"myFile" ofType:#"txt"];
[myString writeToFile:filePath automatically:YES encoding:NSUTF... error:nil];
//now while retrieving it when no internet connection
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"myFile" ofType:#"txt"];
NSString *myString = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF.. error:nil];
now myString returns with #""... why i am not been able to write data?
Best Regards
Whatever you want to do is not possible (or at least strongly discouraged) to update files in the app bundle.
If you’re downloading files and want to store them on the device you should use the Documents directory. You can get the path to this directory with:
- (NSString *)getDocumentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return [paths objectAtIndex:0];
}
First check weather the contents are getting written to file. You can view the file in xcode.
What i suggest is when you run the app create this empty file. Then you can Read and write to that file easily.
Try Using Below code:
NSError* error = nil;
NSString* jsonFileName = [NSString stringWithFormat:#"myfile"];
NSString* jsonPath = [[NSBundle mainBundle] pathForResource:jsonFileName
ofType:#"txt"];
NSString* jsonString = [NSString stringWithContentsOfFile:jsonPath
encoding:NSUTF8StringEncoding error:&error];
Documents directory:
Write to file
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/textfile.txt",
documentsDirectory];
//create content - four lines of text
NSString *content = #"One\nTwo\nThree\nFour\nFive";
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
Display content:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/textfile.txt",
documentsDirectory];
NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
usedEncoding:nil
error:nil];
//NSString *csvString = #"S.No,Task,Date,Time";
//NSArray *csvArray=[csvString componentsSeparatedByString:#","];
// Create .csv file and save in Documents Directory.
NSArray *csvArray =[[NSArray alloc]initWithObjects:#"SNo",#"Task",#"Date",#"Time",nil];
//create instance of NSFileManager
// NSFileManager *fileManager = [NSFileManager defaultManager];
//create an array and store result of our search for the documents directory in it
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//create NSString object, that holds our exact path to the documents directory
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(#"Document Dir: %#",documentsDirectory);
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.csv", #"userdata"]]; //add our file to the path
// [fileManager createFileAtPath:fullPath contents:[csvString dataUsingEncoding:NSUTF8StringEncoding] attributes:nil]; //finally save the path (file)
CHCSVWriter * csvWriter = [[CHCSVWriter alloc] initWithCSVFile:fullPath atomic:NO];
NSInteger numberOfColumns = 4;
for (NSInteger currentIndex = 0; currentIndex < [csvArray count]; currentIndex++) {
id field = [csvArray objectAtIndex:currentIndex];
[csvWriter writeField:field];
if ((currentIndex % numberOfColumns) == (numberOfColumns - 1)) {
[csvWriter writeLine];
}
}
[csvWriter release];
CSV file basically use for making a back up of iphone contacts and it is an Excel file why do you want to make CSV file and if you want, then you have to make an array according to your CSV and for this you have to do study.... well here is code for writing a text in CSV file and save it to in documents directory....
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [path objectAtIndex:0];
NSString *FileName = [NSString stringWithFormat:#"%#/File.csv", documentsDirectory];
NSString *Content = [[NSString alloc] initWithFormat:#"%#", stringForCsv];
//stringForCsv is your string which you want to write in file.
[Content writeToFile:FileName atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];
Thank You!
I would like to know how can i write to a file within Application. The thing im trying to do here is, i am generating a KML (using class XMLWriter from https://github.com/skjolber/xswi). I can log the KML, everythings fine, now what i have to do is, Same this KML to a .kml file, and then email it to some address.
Emailing is no problem, i wanted to know how to write this KML into a .kml file, and then retrieve it for emailing. Can someone help me with a code snippet.
This tutorial did it, more then help.. The Code for generating the .kml file:
NSFileManager *filemgr;
NSData *databuffer;
NSString *dataFile;
NSString *docsDir;
NSArray *dirPaths;
filemgr = [NSFileManager defaultManager];
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
dataFile = [docsDir stringByAppendingPathComponent: #"datafile.kml"];
databuffer = [[xmlWriter toString] dataUsingEncoding: NSASCIIStringEncoding];
[filemgr createFileAtPath: dataFile contents: databuffer attributes:nil];
then to retrieve it i used:
NSFileManager *filemgr;
NSString *dataFile;
NSData *databuffer;
NSString *docsDir;
NSArray *dirPaths;
filemgr = [NSFileManager defaultManager];
// Identify the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the data file
dataFile = [docsDir stringByAppendingPathComponent: #"datafile.kml"];
databuffer = [filemgr contentsAtPath: dataFile];
I believe you've got all your content into a string, if so you can proceed with saving it to .kml file with something like this:
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* fname = [tmp_FileName stringByAppendingFormat: #".kml" ];
NSString* filenameStr = [documentsDirectory
stringByAppendingPathComponent:fname];
[yourKMLString writeToFile: filenameStr atomically: YES];
i have 3NSString objects that i want to save to a new file when the app is running.
this will help me for remote debug!
if any one can help me creating the file and save the data to it will be very use full
thanx
You can save the files to the Documents directory, here is how to get the path to that directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
And a sample write statement:
NSError *error;
BOOL status = [string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
In the NSString documentation there is method called writeToFile:atomically:encoding:error:.
NSError *error;
[#"Write me to file" writeToFile:#"<filepath>" atomically:YES encoding: NSUTF8StringEncoding error:&error];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
NSError *error; BOOL succeed = [myString writeToFile:[documentsDirectory stringByAppendingPathComponent:#"myfile.txt"]
atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!succeed){
// Handle error here }
source.
Here is how to save NSString into Documents folder. Saving other types of data can be also realized that way.
- (void)saveString:(NSString *)stringToSave toDocumentsWithFilename:(NSString *)fileName {
NSString *documentsFolder = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *path = [documentsFolder stringByAppendingPathComponent:fileName];
[[NSFileManager defaultManager] createFileAtPath:path contents:[stringToSave dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
}
Usage:
NSString *stringWeWantToSave = #"This is an elephant";
NSString *fileName = [NSString stringWithString:#"savedString.txt"];
[self saveString:stringWeWantToSave toDocumentsWithFilename:fileName];