I need to export multiple data tables to Excel on the clients machine, each to their own sheet. If it was just one sheet, I'd use the Excel/csv content type, but I've heard something about an XML format that can represent an entire workbook. I don't want to go down the Packaging and .xlsx route, so I need standard .xls.
Our bug tracker, Gemini, used to have an export function that produced an XML file that Excel automatically opened as a multi-sheet workbook, but I can't find it. Is there still such a mechanism, and where can I find that schema?
You can use for example this library, if you don't want to create your own Excel XML writer library.
In Excel you can save a workbook in XML format. (in Excel 2007 it is called XML Spreadsheet 2003).
That might get you started.
USE The Below In seperate class file and on page.cs file paste the the function like this on button click:
ExcelHelperNS.ExcelHelper.ToExcel(Dataset1, "ExcelFileName", Page.Response);
use this in separate class and it will work..
public class ExcelHelper
{
//Row limits older excel verion per sheet, the row limit for excel 2003 is 65536
const int rowLimit = 65000;
private static string getWorkbookTemplate()
{
var sb = new StringBuilder(818);
sb.AppendFormat(#"<?xml version=""1.0""?>{0}", Environment.NewLine);
sb.AppendFormat(#"<?mso-application progid=""Excel.Sheet""?>{0}", Environment.NewLine);
sb.AppendFormat(#"<Workbook xmlns=""urn:schemas-microsoft-com:office:spreadsheet""{0}", Environment.NewLine);
sb.AppendFormat(#" xmlns:o=""urn:schemas-microsoft-com:office:office""{0}", Environment.NewLine);
sb.AppendFormat(#" xmlns:x=""urn:schemas-microsoft-com:office:excel""{0}", Environment.NewLine);
sb.AppendFormat(#" xmlns:ss=""urn:schemas-microsoft-com:office:spreadsheet""{0}", Environment.NewLine);
sb.AppendFormat(#" xmlns:html=""http://www.w3.org/TR/REC-html40"">{0}", Environment.NewLine);
sb.AppendFormat(#" <Styles>{0}", Environment.NewLine);
sb.AppendFormat(#" <Style ss:ID=""Default"" ss:Name=""Normal"">{0}", Environment.NewLine);
sb.AppendFormat(#" <Alignment ss:Vertical=""Bottom""/>{0}", Environment.NewLine);
sb.AppendFormat(#" <Borders/>{0}", Environment.NewLine);
sb.AppendFormat(#" <Font ss:FontName=""Calibri"" x:Family=""Swiss"" ss:Size=""11"" ss:Color=""#000000""/>{0}", Environment.NewLine);
sb.AppendFormat(#" <Interior/>{0}", Environment.NewLine);
sb.AppendFormat(#" <NumberFormat/>{0}", Environment.NewLine);
sb.AppendFormat(#" <Protection/>{0}", Environment.NewLine);
sb.AppendFormat(#" </Style>{0}", Environment.NewLine);
sb.AppendFormat(#" <Style ss:ID=""s62"">{0}", Environment.NewLine);
sb.AppendFormat(#" <Font ss:FontName=""Calibri"" x:Family=""Swiss"" ss:Size=""11"" ss:Color=""#000000""{0}", Environment.NewLine);
sb.AppendFormat(#" ss:Bold=""1""/>{0}", Environment.NewLine);
sb.AppendFormat(#" </Style>{0}", Environment.NewLine);
sb.AppendFormat(#" <Style ss:ID=""s63"">{0}", Environment.NewLine);
sb.AppendFormat(#" <NumberFormat ss:Format=""Short Date""/>{0}", Environment.NewLine);
sb.AppendFormat(#" </Style>{0}", Environment.NewLine);
sb.AppendFormat(#" </Styles>{0}", Environment.NewLine);
sb.Append(#"{0}\r\n</Workbook>");
return sb.ToString();
}
private static string replaceXmlChar(string input)
{
input = input.Replace("&", "&");
input = input.Replace("<", "<");
input = input.Replace(">", ">");
input = input.Replace("\"", """);
input = input.Replace("'", "'");
return input;
}
private static string getCell(Type type, object cellData)
{
var data = (cellData is DBNull) ? "" : cellData;
if (type.Name.Contains("Int") || type.Name.Contains("Double") || type.Name.Contains("Decimal")) return string.Format("<Cell><Data ss:Type=\"Number\">{0}</Data></Cell>", data);
if (type.Name.Contains("Date") && data.ToString() != string.Empty)
{
return string.Format("<Cell ss:StyleID=\"s63\"><Data ss:Type=\"DateTime\">{0}</Data></Cell>", Convert.ToDateTime(data).ToString("yyyy-MM-dd"));
}
return string.Format("<Cell><Data ss:Type=\"String\">{0}</Data></Cell>", replaceXmlChar(data.ToString()));
}
private static string getWorksheets(DataSet source)
{
var sw = new StringWriter();
if (source == null || source.Tables.Count == 0)
{
sw.Write("<Worksheet ss:Name=\"Sheet1\">\r\n<Table>\r\n<Row><Cell><Data ss:Type=\"String\"></Data></Cell></Row>\r\n</Table>\r\n</Worksheet>");
return sw.ToString();
}
foreach (DataTable dt in source.Tables)
{
if (dt.Rows.Count == 0)
sw.Write("<Worksheet ss:Name=\"" + replaceXmlChar(dt.TableName) + "\">\r\n<Table>\r\n<Row><Cell ss:StyleID=\"s62\"><Data ss:Type=\"String\"></Data></Cell></Row>\r\n</Table>\r\n</Worksheet>");
else
{
//write each row data
var sheetCount = 0;
for (int i = 0; i < dt.Rows.Count; i++)
{
if ((i % rowLimit) == 0)
{
//add close tags for previous sheet of the same data table
if ((i / rowLimit) > sheetCount)
{
sw.Write("\r\n</Table>\r\n</Worksheet>");
sheetCount = (i / rowLimit);
}
sw.Write("\r\n<Worksheet ss:Name=\"" + replaceXmlChar(dt.TableName) +
(((i / rowLimit) == 0) ? "" : Convert.ToString(i / rowLimit)) + "\">\r\n<Table>");
//write column name row
sw.Write("\r\n<Row>");
foreach (DataColumn dc in dt.Columns)
sw.Write(string.Format("<Cell ss:StyleID=\"s62\"><Data ss:Type=\"String\">{0}</Data></Cell>", replaceXmlChar(dc.ColumnName)));
sw.Write("</Row>");
}
sw.Write("\r\n<Row>");
foreach (DataColumn dc in dt.Columns)
sw.Write(getCell(dc.DataType, dt.Rows[i][dc.ColumnName]));
sw.Write("</Row>");
}
sw.Write("\r\n</Table>\r\n</Worksheet>");
}
}
return sw.ToString();
}
public static string GetExcelXml(DataTable dtInput, string filename)
{
var excelTemplate = getWorkbookTemplate();
var ds = new DataSet();
ds.Tables.Add(dtInput.Copy());
var worksheets = getWorksheets(ds);
var excelXml = string.Format(excelTemplate, worksheets);
return excelXml;
}
public static string GetExcelXml(DataSet dsInput, string filename)
{
var excelTemplate = getWorkbookTemplate();
var worksheets = getWorksheets(dsInput);
var excelXml = string.Format(excelTemplate, worksheets);
return excelXml;
}
public static void ToExcel(DataSet dsInput, string filename, HttpResponse response)
{
var excelXml = GetExcelXml(dsInput, filename);
response.Clear();
response.AppendHeader("Content-Type", "application/vnd.ms-excel");
response.AppendHeader("Content-disposition", "attachment; filename=" + filename);
response.Write(excelXml);
response.Flush();
response.End();
}
public static void ToExcel(DataTable dtInput, string filename, HttpResponse response)
{
var ds = new DataSet();
ds.Tables.Add(dtInput.Copy());
ToExcel(ds, filename, response);
}
}
Related
I need some help searching / filtering a Core data entity. The results array returns Null..
I have a root view with a search bar, controller and tableview. This view shows normally.
I'm calling the UISearchBarDelegate and the UISearchDisplayDelegate.
I have a mutable array (searchResults).
My search code is as follows:
-(void) filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSLog(#"%s", __FUNCTION__);
[self.searchResults removeAllObjects];
for (Entity *ent in [self.fetchedResultsController fetchedObjects])
{
if ([scope isEqualToString:#"All"] || [ent.title isEqualToString:scope])
{
NSRange range = [ent.title rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (range.location != NSNotFound)
{
NSLog(#"Adding title '%#' to searchResults as it contains '%#'", ent.title, searchText);
[self.searchResults addObject:ent];
}
}
}
NSLog(#"The searchResults array contains '%#'", searchResults); <<<< RETURNS NULL
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString scope:#"All"];
return YES;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
[self filterContentForSearchText:[self.searchDisplayController.searchBar text ]scope:#"All"];
return YES;
}
and the cell config code is:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"MyVeryOwnCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
Entity *entity = nil;
if (tableView == self.searchDisplayController.searchResultsTableView)
{
//NSLog(#"Configuring cell to show search results");
entity = [self.searchResults objectAtIndex:indexPath.row];
}
else
{
//NSLog(#"Configuring cell to show normal data");
entity = [self.fetchedResultsController objectAtIndexPath:indexPath];
}
cell.textLabel.text = entity.title;
return cell;
}
I must be doing something dumb as the searchResults array appears to be null. I would appreciate any advice.
You just forgot to alloc/init the searchResults array.
;-)
I have a UIWebView that loads text from an htmlString.
I need when the user selects a part of the text and presses a button, i will be capable of extracting it in order to use it elsewhere, so i am using this code :
// The JS File
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"HighlightedString" ofType:#"js" inDirectory:#""];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSString *jsString = [[NSMutableString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
[WebV2 stringByEvaluatingJavaScriptFromString:jsString];
// The JS Function
NSString *startSearch = [NSString stringWithFormat:#"getHighlightedString()"];
[WebV2 stringByEvaluatingJavaScriptFromString:startSearch];
NSString *selectedText = [NSString stringWithFormat:#"selectedText"];
NSString * highlightedString = [WebV2 stringByEvaluatingJavaScriptFromString:selectedText];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Highlighted String"
message:highlightedString
delegate:nil
cancelButtonTitle:#"Oh Yeah"
otherButtonTitles:nil];
[alert show];
Along with HighlightedString.js :
/*!
------------------------------------------------------------------------
// Search Highlighted String
------------------------------------------------------------------------
*/
var selectedText = "";
function getHighlightedString() {
var text = window.getSelection();
selectedText = text.anchorNode.textContent.substr(text.anchorOffset, text.focusOffset - text.anchorOffset);
}
// ...
function stylizeHighlightedString() {
var range = window.getSelection().getRangeAt(0);
var selectionContents = range.extractContents();
var span = document.createElement("span");
span.appendChild(selectionContents);
span.setAttribute("class","uiWebviewHighlight");
span.style.backgroundColor = "black";
span.style.color = "white";
range.insertNode(span);
}
// helper function, recursively removes the highlights in elements and their childs
function uiWebview_RemoveAllHighlightsForElement(element) {
if (element) {
if (element.nodeType == 1) {
if (element.getAttribute("class") == "uiWebviewHighlight") {
var text = element.removeChild(element.firstChild);
element.parentNode.insertBefore(text,element);
element.parentNode.removeChild(element);
return true;
} else {
var normalize = false;
for (var i=element.childNodes.length-1; i>=0; i--) {
if (uiWebview_RemoveAllHighlightsForElement(element.childNodes[i])) {
normalize = true;
}
}
if (normalize) {
element.normalize();
}
}
}
}
return false;
}
// the main entry point to remove the highlights
function uiWebview_RemoveAllHighlights() {
selectedText = "";
uiWebview_RemoveAllHighlightsForElement(document.body);
}
I always get nothing as a result ... The alert view shows nothing...What's the problem with this code ? Any help ? Any ideas ? It will be really appreciated.
The solution was actually pretty simple and no need for all the above code!
For any future users just use:
NSString *textToSpeech = [WebV2 stringByEvaluatingJavaScriptFromString: #"window.getSelection().toString()"];
NSLog(#" -**-*--****-*---**--*-* This is the new select text %#",[WebV2 stringByEvaluatingJavaScriptFromString: #"window.getSelection().toString()"] );
NSString *theSelectedText = [self.webView stringByEvaluatingJavaScriptFromString:#"window.getSelection().toString()"];
This will pass your selection to the string variable.
Hei guys,
I'm trying to load a long text from a .rtf file and I want to show this text in a UITextView.
I store all the .rtf files in a folder called "rtf" into the "Supporting Files" folder.
This is my code.
- (void)setDetailItem:(id)newDetailItem
{
if (_detailItem != newDetailItem) {
_detailItem = newDetailItem;
// Update the view.
[self configureView];
}
}
- (void)configureView
{
// Update the user interface for the detail item.
if (self.detailItem)
{
self.textView.text = [self setTextForTextView:[self.detailItem description]];
}
}
-(NSString *)setTextForTextView:(NSString *)description
{
NSString *path = [NSString stringWithFormat:#"rtf/%#.rtf" ,description];
NSLog(#"%#" ,path);
NSString *myText = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
return myText;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.title = #"Text";
// Do any additional setup after loading the view, typically from a nib.
[self configureView];
}
But It doesn't show me the text and I don't understand why...
Thanks!
I just solved in this way:
-(NSString *)setTextForTextView:(NSString *)description
{
NSString *filePath = [[NSBundle mainBundle] pathForResource:description ofType:#"txt"];
if (filePath)
{
NSString *myText = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
if (myText)
{
return myText;
}
}
}
I hope this will help some people in the future! :D
What i have so far is
#synthesize txtCountry,txtState;
int flgTextField;
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
[pickerView reloadAllComponents];
// Make a new view, or do what you want here
if(textField == txtCountry || textField == txtState){
flgTextField = textField.tag;
[UIView beginAnimations:nil context:NULL];
//[pvState setFrame:CGRectMake(0.0f, 199.0f, 320.0f, 216.0f)];
[UIView commitAnimations];
return NO;
}
else {
return YES;
}
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {
if(flgTextField==1){
return [arryCountry count];
}
else {
return [arryState count];
}
}
- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
if(flgTextField==1){
return [arryCountry objectAtIndex:row];
}
else{
return [arryState objectAtIndex:row];
}
}
- (void)viewDidLoad {
arryCountry = [[NSMutableArray alloc] init];
arryState = [[NSMutableArray alloc] init];
[arryCountry addObject:#" 100 "];
[arryCountry addObject:#" 200 "];
[arryCountry addObject:#" 400 "];
[arryCountry addObject:#" 600 "];
[arryCountry addObject:#" 1000 "];
[arryState addObject:#" a "];
[arryState addObject:#" b "];
[arryState addObject:#" c "];
[arryState addObject:#" d "];
[arryState addObject:#" e "];
[super viewDidLoad];
}
in my .m
and
#interface Contact : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource> {
IBOutlet UITextField *txtCountry;
IBOutlet UITextField *txtState;
NSMutableArray *arryCountry;
NSMutableArray *arryState;
UIPickerView *pickerView;
}
#property(nonatomic,retain) IBOutlet UITextField *txtCountry;
#property(nonatomic,retain) IBOutlet UITextField *txtState;
in my .h file
Now the text fields are not editable and I need some help or guidance, or any tutorial on how to connect UIPicker with multiple sources that can be change when text fields are editing
So i see no one cares :)
what i have now is 3 textFields and whenever i touch textField1 or textField2 Picker changes values and there is no keyboard. When i touch textField3 keyboard appears and the picker goes hidden.Now if i dismiss the keyboard by clicking return and then click textField1 picker appears again, but if i dont dismiss the keyboard BY CLICKING BUTTON it stays over the picker. What I need is when the keyboard is firstResponder (and i see it on the screen) to hide it if i click on the textField1 and only to see the picker
int variabla;
-(void)textFieldDidBeginEditing:(UITextField *)textField{
[pickerView setHidden:YES];
if (textField1.editing == YES) {
[textField1 resignFirstResponder];
[pickerView setHidden:NO];
variabla = 1;
}else if (textField2.editing == YES) {
[textField2 resignFirstResponder];
[pickerView setHidden:NO];
variabla = 2;
}
NSLog(#"variabla %d",variabla);
[pickerView reloadAllComponents];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
{
if (variabla == 1) {
return [pickerArray1 count];
}else if (variabla == 2) {
return [pickerArray2 count];
}else {
return 0;
}
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
{
if (variabla == 1) {
return [pickerArray1 objectAtIndex:row];
}else if (variabla == 2) {
return [pickerArray2 objectAtIndex:row];
}else {
return 0;
}
}
- (void)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
}
- (void)viewDidLoad {
[super viewDidLoad];
[pickerView setHidden:YES];
pickerArray1 = [[NSMutableArray alloc] initWithObjects:#"0", #"1", #"2", nil];
pickerArray2 = [[NSMutableArray alloc] initWithObjects:#"3", #"4", #"5", nil];
}
I have an app that has a tab bar, each tab contains a separate table. The first table uses core data to persist its entries and checkmarks. The second table on the second tab uses an NSMutableArray to populate it (I would use core data but I would have to pre populate it and this table does not allow that) I would like to persist check marks the same way I do in the first table with core data but something is wrong. The code looks like this:
-(void)viewDidLoad {
[super viewDidLoad];
airport = [[NSMutableArray alloc] init];
[airport addObject:#"Passport"];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [airport count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Set up the cell...
NSString *cellValue = [airport objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
//[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
NSManagedObject *item = [[self fetchedResultsController] objectAtIndexPath:indexPath];
cell.textLabel.text = [item valueForKey:#"name"]; //CHANGED TO DETAIL
if ([[item valueForKey:#"check"] boolValue]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSManagedObject *selectedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
if ([[selectedObject valueForKey:#"check"] boolValue]) {
[selectedObject setValue:[NSNumber numberWithBool:NO] forKey:#"check"];
} else {
[selectedObject setValue:[NSNumber numberWithBool:YES] forKey:#"check"];
}
UITableViewCell *thisCell = [tableView cellForRowAtIndexPath:indexPath];
if (thisCell.accessoryType == UITableViewCellAccessoryNone) {
thisCell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
thisCell.accessoryType = UITableViewCellAccessoryNone;
}
[tableView deselectRowAtIndexPath:indexPath animated:NO];
}
I believe the line cell.textLabel.text = [item valueForKey#"name"];
is whats causing it. All that I would like for this to do is have the table populated from the array and check marks persisted. Any help is GREATLY appreciated. Thanks in advance.
This line is replacing the cell text:
cell.textLabel.text = [item valueForKey:#"name"];
that was initially assigned by these lines:
NSString *cellValue = [airport objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
Why are your using the "name" property of "item"?