I expect once clicking the toolbar button like "Mapa", annotations will show in the visible map region. Data are fetched from CoreData (Sqlite). Everything works fine in iPhone Simulator, but when I test the app on my iPhone just some pins are displayed after clicking the button on toolbar and I need to zoom in and out several times to obtain all the pins.
the first image (http://www.aerodromoschile.com/IMG_0982.PNG) shows the screen before zoom it several times and the second (http://www.aerodromoschile.com/IMG_0981.PNG) is what I want to get from the begining
could you help me? here is the code
#import "MapViewController.h"
#import "AerodromoAppDelegate.h"
#import "Aerodromo.h"
#import "DetalleViewController.h"
#import <MapKit/MapKit.h>
#implementation mapViewController {
NSArray *locations;
}
#synthesize managedObjectContext;
#synthesize mapView;
- (void)viewDidLoad
{
[super viewDidLoad];
if (self.managedObjectContext == nil)
{
self.managedObjectContext = [(AerodromoAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSLog(#"After managedObjectContext: %#", self.managedObjectContext);
}
dispatch_async (dispatch_get_main_queue(), ^{
NSLog(#"Main Thread Code");
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Aerodromo" inManagedObjectContext:self.managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *foundObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (foundObjects == nil) {
NSLog(#"FATAL_CORE_DATA_ERROR(error)");
return;
}
if (locations != nil) {
[self.mapView removeAnnotations:locations];
}
locations = foundObjects;
self.title = #"Mapa Online";
UIBarButtonItem *showuser = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(showUser:)];
UIBarButtonItem *boton = [[UIBarButtonItem alloc] initWithTitle:#"Boton" style:UIBarButtonItemStyleDone target:self action:#selector(boton2:)];
NSArray *botones = [[NSArray alloc] initWithObjects:showuser, boton, nil];
self.navigationItem.rightBarButtonItems = botones;
mapView.delegate = self;
// Creamos una coordenada inicial.
CLLocationCoordinate2D initialLocation;
MKCoordinateRegion region = {{0.0f, 0.0f}, {0.0f, 0.0f}};
region.center = self.mapView.userLocation.location.coordinate;
initialLocation.latitude = self.mapView.userLocation.location.coordinate.latitude;
initialLocation.longitude= self.mapView.userLocation.location.coordinate.longitude;
// Esto situarĂ¡ el centro del mapa
region = MKCoordinateRegionMakeWithDistance(initialLocation, 50000, 50000);
[self.mapView setRegion:region animated:NO];
[self.mapView removeAnnotations:self.mapView.annotations];
NSLog(#"antotaciones = %d", locations.count);
[self.mapView addAnnotations:locations];
self.mapView.showsUserLocation=TRUE;
NSLog(#"fin Thread Code");
}); // termino del queqe
//[self.mapView addAnnotations:locations];
//[self updateLocations];
}
- (void)showUser:(id)sender{
NSLog(#"Boton1");
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(self.mapView.userLocation.coordinate, 50000, 50000);
[self.mapView setRegion:[self.mapView regionThatFits:region] animated:NO];
}
- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
{
[self.mapView removeAnnotations:self.mapView.annotations];
[self.mapView addAnnotations:locations];
}
- (void)boton2:(id)sender{
NSLog(#"boton 2");
}
#pragma mark - MKMapViewDelegate
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[Aerodromo class]]) {
static NSString *identifier = #"Aerodromo";
MKAnnotationView *annotationView = (MKPinAnnotationView *)[self.mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
if (annotationView == nil) {
annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
annotationView.enabled = YES;
annotationView.canShowCallout = YES;
//annotationView.animatesDrop = NO;
annotationView.image = [UIImage imageNamed:#"aero3.png"];
//annotationView.pinColor = MKPinAnnotationColorGreen;
UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton addTarget:self action:#selector(showLocationDetails:) forControlEvents:UIControlEventTouchUpInside];
annotationView.rightCalloutAccessoryView = rightButton;
} else {
annotationView.annotation = annotation;
}
UIButton *button = (UIButton *)annotationView.rightCalloutAccessoryView;
button.tag = [locations indexOfObject:(Aerodromo *)annotation];
return annotationView;
}
return nil;
}
- (void)showLocationDetails:(UIButton *)button
{
NSLog(#"se apreto el boton");
//[self performSegueWithIdentifier:#"EditLocation" sender:button];
}
#end
EDITED CODE
this is the las code that I'm using, I sill have the same problem....
- (void)viewDidLoad
{
[super viewDidLoad];
if (self.managedObjectContext == nil)
{
self.managedObjectContext = [(AerodromoAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSLog(#"After managedObjectContext: %#", self.managedObjectContext);
}
UIBarButtonItem *showuser = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(showUser:)];
UIBarButtonItem *boton = [[UIBarButtonItem alloc] initWithTitle:#"Boton" style:UIBarButtonItemStyleDone target:self action:#selector(boton2:)];
NSArray *botones = [[NSArray alloc] initWithObjects:showuser, boton, nil];
self.navigationItem.rightBarButtonItems = botones;
self.title = #"Mapa Online";
mapView.delegate = self;
// Creamos una coordenada inicial.
CLLocationCoordinate2D initialLocation;
MKCoordinateRegion region = {{0.0f, 0.0f}, {0.0f, 0.0f}};
//region.center = //self.mapView.userLocation.location.coordinate;
initialLocation.latitude = -33.40;//self.mapView.userLocation.location.coordinate.latitude;
initialLocation.longitude= -70.54;//self.mapView.userLocation.location.coordinate.longitude;
// Esto situarĂ¡ el centro del mapa
region = MKCoordinateRegionMakeWithDistance(initialLocation, 50000, 50000);
[self.mapView setRegion:region animated:NO];
self.mapView.showsUserLocation=TRUE;
[self.mapView removeAnnotations:self.mapView.annotations];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
//Anything that is not part of the UI
NSLog(#"ASync Thread Code");
NSMutableArray *tempLocations = [[NSMutableArray alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Aerodromo" inManagedObjectContext:self.managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *foundObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (foundObjects == nil) {
NSLog(#"FATAL_CORE_DATA_ERROR(error)");
return;
}
MKPointAnnotation *location; //If you're not using MKPointAnnotation: replace it
for (location in foundObjects) {
[tempLocations addObject:location];
}
locations = tempLocations.copy;
dispatch_sync(dispatch_get_main_queue(), ^{
//Update the UI
NSLog(#"Getting back to the UI");
NSLog(#"antotaciones = %d, %#", locations.count, locations);
if (locations != nil) {
[self.mapView removeAnnotations:self.mapView.annotations];
[self.mapView addAnnotations:locations];
}
});
});
NSLog(#"fin Thread Code");
}
Thanks for your help wkberg, when I used NSLog(#"antotaciones = %d, %#", locations.count, locations); to know what happen with the data I realized that after the 7th row the NSFetchRequest does not load the data
here is the console:
2013-07-16 12:10:18.007 Aerodromo[13922:1207] ASync Thread Code
2013-07-16 12:10:18.045 Aerodromo[13922:907] Getting back to the UI
2013-07-16 12:10:18.090 Aerodromo[13922:907] antotaciones = 351, (
"<Aerodromo: 0x1f0b0040> (entity: Aerodromo; id: 0x1f0ad580 <x-coredata://DEC0D4FE-F4A8-4739-9974-076071695E99/Aerodromo/p1> ; data: {\n Ancho1 = 45;\n Ancho2 = \"\";\n Ancho3 = \"\";\n Ciudad = \"Arica \";\n Desig = SCAR;\n Elev = \"123 -166\";\n FrecTerr = IFR;\n FrecTorre = 1;\n Fuel = JP1;\n Fuel2 = \"AVGAS 100/130\";\n IdAd = 1;\n IndexRegion = 1;\n Larg1 = 2170;\n Larg2 = \"\";\n Larg3 = \"\";\n LatG = 18;\n LatM = 20;\n LatS = 55;\n Latitud = \"-18.349\";\n Limitaciones = \"\";\n Limitaciones2 = \"\";\n Limitaciones3 = \"\";\n LonG = 70;\n LonM = 20;\n LonS = 19;\n Longitud = \"-70.339\";\n Nombre = Chacalluta;\n NumeroPistas = 1;\n Pista1 = \"02-20\";\n Pista2 = \"\";\n Pista3 = \"\";\n RegionOrd = 15;\n Superficie = \"Hormig\\U00f3n\";\n Superficie2 = \"\";\n Superficie3 = \"\";\n Telefono = \"(58) 211116\";\n TieneMetar = 1;\n Uso = \"P\\U00daBLICO\";\n frec = \"<relationship fault: 0x21d8e110 'frec'>\";\n pdf = \"<relationship fault: 0x21d8e460 'pdf'>\";\n})",
"<Aerodromo: 0x1f0b0470> (entity: Aerodromo; id: 0x1f098d30 <x-coredata://DEC0D4FE-F4A8-4739-9974-076071695E99/Aerodromo/p2> ; data: {\n Ancho1 = 23;\n Ancho2 = \"\";\n Ancho3 = \"\";\n Ciudad = \"Arica \";\n Desig = SCAE;\n Elev = 328;\n FrecTerr = 0;\n FrecTorre = 0;\n Fuel = \"No Tiene\";\n Fuel2 = \"\";\n IdAd = 2;\n IndexRegion = 1;\n Larg1 = 800;\n Larg2 = \"\";\n Larg3 = \"\";\n LatG = 18;\n LatM = 30;\n LatS = 36;\n Latitud = \"-18.51\";\n Limitaciones = \"\";\n Limitaciones2 = \"\";\n Limitaciones3 = \"\";\n LonG = 70;\n LonM = 17;\n LonS = 21;\n Longitud = \"-70.289\";\n Nombre = \"El Buitre\";\n NumeroPistas = 1;\n Pista1 = \"09-27\";\n Pista2 = \"\";\n Pista3 = \"\";\n RegionOrd = 15;\n Superficie = Asfalto;\n Superficie2 = \"\";\n Superficie3 = \"\";\n Telefono = \"(58) 201500 Anexo 31216\";\n TieneMetar = 0;\n Uso = MILITAR;\n frec = \"<relationship fault: 0x21e711e0 'frec'>\";\n pdf = \"<relationship fault: 0x21e715e0 'pdf'>\";\n})",
"<Aerodromo: 0x1f0b0870> (entity: Aerodromo; id: 0x1f0a09c0 <x-coredata://DEC0D4FE-F4A8-4739-9974-076071695E99/Aerodromo/p3> ; data: {\n Ancho1 = 45;\n Ancho2 = \"\";\n Ancho3 = \"\";\n Ciudad = \"Iquique \";\n Desig = SCDA;\n Elev = \"97-157\";\n FrecTerr = \"VFR - IFR\";\n FrecTorre = 1;\n Fuel = JP1;\n Fuel2 = \"AVGAS 100/130\";\n IdAd = 3;\n IndexRegion = 2;\n Larg1 = 3350;\n Larg2 = \"\";\n Larg3 = \"\";\n LatG = 20;\n LatM = 32;\n LatS = 07;\n Latitud = \"-20.535\";\n Limitaciones = \"\";\n Limitaciones2 = \"\";\n Limitaciones3 = \"\";\n LonG = 70;\n LonM = 10;\n LonS = 53;\n Longitud = \"-70.181\";\n Nombre = \"Diego Aracena\";\n NumeroPistas = 1;\n Pista1 = \"19-01\";\n Pista2 = \"\";\n Pista3 = \"\";\n RegionOrd = 1;\n Superficie = \"Hormig\\U00f3n\";\n Superficie2 = \"\";\n Superficie3 = \"\";\n Telefono = \"(57)461200\";\n TieneMetar = 1;\n Uso = \"P\\U00daBLICO\";\n frec = \"<relationship fault: 0x21e71d00 'frec'>\";\n pdf = \"<relationship fault: 0x21e71e70 'pdf'>\";\n})",
"<Aerodromo: 0x1f0b0670> (entity: Aerodromo; id: 0x1f0a09a0 <x-coredata://DEC0D4FE-F4A8-4739-9974-076071695E99/Aerodromo/p4> ; data: {\n Ancho1 = 20;\n Ancho2 = 20;\n Ancho3 = \"\";\n Ciudad = \"Pica \";\n Desig = SCKP;\n Elev = 12468;\n FrecTerr = 0;\n FrecTorre = 0;\n Fuel = \"No Tiene\";\n Fuel2 = \"\";\n IdAd = 4;\n IndexRegion = 2;\n Larg1 = 3200;\n Larg2 = 1034;\n Larg3 = \"\";\n LatG = 20;\n LatM = 44;\n LatS = 08;\n Latitud = \"-20.736\";\n Limitaciones = \"\";\n Limitaciones2 = \"\";\n Limitaciones3 = \"\";\n LonG = 68;\n LonM = 41;\n LonS = 42;\n Longitud = \"-68.69499999999999\";\n Nombre = Coposa;\n NumeroPistas = 2;\n Pista1 = \"17-35\";\n Pista2 = \"10-28\";\n Pista3 = \"\";\n RegionOrd = 1;\n Superficie = Asfalto;\n Superficie2 = Tierra;\n Superficie3 = \"\";\n Telefono = \"(57)417777\";\n TieneMetar = 0;\n Uso = PRIVADO;\n frec = \"<relationship fault: 0x21e72b80 'frec'>\";\n pdf = \"<relationship fault: 0x21e72f70 'pdf'>\";\n})",
"<Aerodromo: 0x1f0b0a50> (entity: Aerodromo; id: 0x1f0907c0 <x-coredata://DEC0D4FE-F4A8-4739-9974-076071695E99/Aerodromo/p5> ; data: {\n Ancho1 = 30;\n Ancho2 = \"\";\n Ancho3 = \"\";\n Ciudad = \"Pozo Almonte\";\n Desig = SCNV;\n Elev = 3172;\n FrecTerr = 0;\n FrecTorre = 0;\n Fuel = \"No Tiene\";\n Fuel2 = \"\";\n IdAd = 5;\n IndexRegion = 2;\n Larg1 = 1077;\n Larg2 = \"\";\n Larg3 = \"\";\n LatG = 20;\n LatM = 44;\n LatS = \"05,4\";\n Latitud = \"-20.735\";\n Limitaciones = \"\";\n Limitaciones2 = \"\";\n Limitaciones3 = \"\";\n LonG = 69;\n LonM = 37;\n LonS = \"32,6\";\n Longitud = \"-69.626\";\n Nombre = \"Nueva Victoria\";\n NumeroPistas = 1;\n Pista1 = \"09-27\";\n Pista2 = \"\";\n Pista3 = \"\";\n RegionOrd = 1;\n Superficie = Vichufita;\n Superficie2 = \"\";\n Superficie3 = \"\";\n Telefono = \"(57) 413620\";\n TieneMetar = 0;\n Uso = PRIVADO;\n frec = \"<relationship fault: 0x21e739e0 'frec'>\";\n pdf = \"<relationship fault: 0x21e73800 'pdf'>\";\n})",
"<Aerodromo: 0x1f0b0c20> (entity: Aerodromo; id: 0x1f0920e0 <x-coredata://DEC0D4FE-F4A8-4739-9974-076071695E99/Aerodromo/p6> ; data: {\n Ancho1 = 18;\n Ancho2 = \"\";\n Ancho3 = \"\";\n Ciudad = \"Antofagasta \";\n Desig = SCGU;\n Elev = 3347;\n FrecTerr = 0;\n FrecTorre = 0;\n Fuel = \"No Tiene\";\n Fuel2 = \"\";\n IdAd = 6;\n IndexRegion = 3;\n Larg1 = 1200;\n Larg2 = \"\";\n Larg3 = \"\";\n LatG = 24;\n LatM = 8;\n LatS = 11;\n Latitud = \"-24.136\";\n Limitaciones = \"\";\n Limitaciones2 = \"\";\n Limitaciones3 = \"\";\n LonG = 69;\n LonM = 49;\n LonS = 43;\n Longitud = \"-69.82899999999999\";\n Nombre = \"Aguas Blancas\";\n NumeroPistas = 1;\n Pista1 = \"13-31\";\n Pista2 = \"\";\n Pista3 = \"\";\n RegionOrd = 2;\n Superficie = Tierra;\n Superficie2 = \"\";\n Superficie3 = \"\";\n Telefono = \"(2) 2063737\";\n TieneMetar = 0;\n Uso = PRIVADO;\n frec = \"<relationship fault: 0x21e744d0 'frec'>\";\n pdf = \"<relationship fault: 0x21e74920 'pdf'>\";\n})",
"<Aerodromo: 0x1f0b1020> (entity: Aerodromo; id: 0x1f0a1970 <x-coredata://DEC0D4FE-F4A8-4739-9974-076071695E99/Aerodromo/p7> ; data: {\n Ancho1 = 50;\n Ancho2 = \"\";\n Ancho3 = \"\";\n Ciudad = \"Antofagasta \";\n Desig = SCFA;\n Elev = \"352- 455\";\n FrecTerr = \"VFR - IFR\";\n FrecTorre = 1;\n Fuel = JP1;\n Fuel2 = \"AVGAS 100/130\";\n IdAd = 7;\n IndexRegion = 3;\n Larg1 = 2599;\n Larg2 = \"\";\n Larg3 = \"\";\n LatG = 23;\n LatM = 26;\n LatS = 40;\n Latitud = \"-23.444\";\n Limitaciones = \"\";\n Limitaciones2 = \"\";\n Limitaciones3 = \"\";\n LonG = 70;\n LonM = 26;\n LonS = 42;\n Longitud = \"-70.44499999999999\";\n Nombre = \"Cerro Moreno\";\n NumeroPistas = 1;\n Pista1 = \"01-19\";\n Pista2 = \"\";\n Pista3 = \"\";\n RegionOrd = 2;\n Superficie = Asfalto;\n Superficie2 = \"\";\n Superficie3 = \"\";\n Telefono = \"(55) 269077\";\n TieneMetar = 1;\n Uso = \"P\\U00daBLICO\";\n frec = \"<relationship fault: 0x21e75370 'frec'>\";\n pdf = \"<relationship fault: 0x21e75190 'pdf'>\";\n})",
"<Aerodromo: 0x1f0b1770> (entity: Aerodromo; id: 0x1f0a41c0 <x-coredata://DEC0D4FE-F4A8-4739-9974-076071695E99/Aerodromo/p8> ; data: <fault>)",
"<Aerodromo: 0x1f0b1f00> (entity: Aerodromo; id: 0x1f0ad660 <x-coredata://DEC0D4FE-F4A8-4739-9974-076071695E99/Aerodromo/p9> ; data: <fault>)",
"<Aerodromo: 0x1f0b11e0> (entity: Aerodromo; id: 0x1f071c50 <x-coredata://DEC0D4FE-F4A8-4739-9974-076071695E99/Aerodromo/p10> ; data: <fault>)",
"<Aerodromo: 0x1f0b1b50> (entity: Aerodromo; id: 0x1f0a4930 <x-coredata://DEC0D4FE-F4A8-4739-9974-076071695E99/Aerodromo/p11> ; data: <fault>)",
"<Aerodromo: 0x1f0b13c0> (entity: Aerodromo; id: 0x1f0a3190 <x-coredata://DEC0D4FE-F4A8-4739-9974-076071695E99/Aerodromo/p12> ; data: <fault>)",
Your dispatching the addAnnotations async. Annotations are part of the UI and should be on the main-thread. The reason they're not added until you zoom the map is because of your regionWillChangeAnimated code. By the time you zoom the async dispatch is finished on the iPhone, but it isn't at the moment when you're adding the annotations in viewDidLoad.
To solve your problem with the GCD:
In your viewDidLoad do something like this:
-(void)viewDidLoad {
//Do UI stuff here:
//the mapView setup
//Region set
//and any other UI like: UILabels, UIbuttons etc.
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//So now we start the async part:
dispatch_async(queue, ^{
//Anything that is not part of the UI
//Get your data for the annotations
//And now get back to the main_queue sync:
dispatch_sync(dispatch_get_main_queue(), ^{
locations = foundObjects; //As in your code
//Update the UI
NSLog(#"Getting back to the UI");
if (locations != nil) {
[self.mapView removeAnnotations:self.mapView.annotations]; //mapView.annotations to remove all...
[self.mapView addAnnotations:locations];
}
});
});
NSLog(#"End of viewDidLoad");
}
From comments:
If still not all the annotations show up. Check if you're not calling [self.mapView addAnnotations:locations]; before your locations array is finished.
This could be done by regionWillChangeAnimated when adjusting the map to the users locations with your: setRegion:region.
NSFetch Problem:
Ok as I'm less familiar with NSFetchRequest, please bear with me:
I believe your NSFetchRequest isn't populating your locations array with all annotations at once.
Try using a NSMutableArray. I've updated the code:
NSMutableArray *tempLocations = [[NSMutableArray alloc] init];
//Do your fetchRequest
//Then do the following, however I don't know exactly as what your `locations` are stored so you might need to change it a bit:
//I believe your annotations are kind of a Aerodromo class? So then:
for (Aerodromo *aerodromoAnn in fetchedObjects) {
[tempLocations addObject:aerodromoAnn];
}
/
//Then update your original locations array:
locations = tempLocations.copy;
//update the main queue again
Sorry you'll have to check as I can't test it without the database
Related
I have a requirement for export data to excel using open Xml plug in. And I want to style excel head boarder colour. I tried different method to achieve my requirement. Its done, But I couldn't not style particular cells (or columns). I have to add boarder and background to my excel cell.
My Code as following
public ActionResult exxx()
{
MemoryStream ms = new MemoryStream();
SpreadsheetDocument xl = SpreadsheetDocument.Create(ms, SpreadsheetDocumentType.Workbook);
WorkbookPart wbp = xl.AddWorkbookPart();
WorksheetPart wsp = wbp.AddNewPart<WorksheetPart>();
Workbook wb = new Workbook();
FileVersion fv = new FileVersion();
fv.ApplicationName = "Microsoft Office Excel";
Worksheet ws = new Worksheet();
//First cell
SheetData sd = new SheetData();
Row r1 = new Row() { RowIndex = (UInt32Value)1u };
Cell c1 = new Cell();
c1.DataType = CellValues.String;
c1.CellValue = new CellValue("some value");
r1.Append(c1);
// Second cell
Cell c2 = new Cell();
c2.CellReference = "C1";
c2.DataType = CellValues.String;
c2.CellValue = new CellValue("other value");
r1.Append(c2);
sd.Append(r1);
//third cell
Row r2 = new Row() { RowIndex = (UInt32Value)2u };
Cell c3 = new Cell();
c3.DataType = CellValues.String;
c3.CellValue = new CellValue("some string");
Cell c4 = new Cell();
c4.DataType = CellValues.String;
c4.CellValue = new CellValue("some car");
r2.Append(c3);
r2.Append(c4);
sd.Append(r2);
ws.Append(sd);
wsp.Worksheet = ws;
wsp.Worksheet.Save();
Sheets sheets = new Sheets();
Sheet sheet = new Sheet();
sheet.Name = "first sheet";
sheet.SheetId = 1;
sheet.Id = wbp.GetIdOfPart(wsp);
sheets.Append(sheet);
wb.Append(fv);
wb.Append(sheets);
xl.WorkbookPart.Workbook = wb;
xl.WorkbookPart.Workbook.Save();
xl.Close();
string fileName = "getdata.xlsx";
Response.Clear();
byte[] dt = ms.ToArray();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));
Response.BinaryWrite(dt);
Response.End();
return File(dt, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "getdata.xlsx");
}
My expected result:
enter image description here
You need to create the style part and reference it by Cell c1 = new Cell() { StyleIndex = (UInt32Value)1U };.
Check
public ActionResult CreateExcel()
{
MemoryStream ms = new MemoryStream();
SpreadsheetDocument xl = SpreadsheetDocument.Create(ms, SpreadsheetDocumentType.Workbook);
WorkbookPart wbp = xl.AddWorkbookPart();
WorkbookStylesPart workbookStylesPart1 = wbp.AddNewPart<WorkbookStylesPart>("rId3");
GenerateWorkbookStylesPart1Content(workbookStylesPart1);
WorksheetPart wsp = wbp.AddNewPart<WorksheetPart>();
Workbook wb = new Workbook();
FileVersion fv = new FileVersion();
fv.ApplicationName = "Microsoft Office Excel";
Worksheet ws = new Worksheet();
//First cell
SheetData sd = new SheetData();
Row r1 = new Row() { RowIndex = (UInt32Value)1u };
Cell c1 = new Cell() { StyleIndex = (UInt32Value)1U };
c1.DataType = CellValues.String;
c1.CellValue = new CellValue("some value");
r1.Append(c1);
// Second cell
Cell c2 = new Cell() { StyleIndex = (UInt32Value)1U };
c2.CellReference = "C1";
c2.DataType = CellValues.String;
c2.CellValue = new CellValue("other value");
r1.Append(c2);
sd.Append(r1);
//third cell
Row r2 = new Row() { RowIndex = (UInt32Value)2u };
Cell c3 = new Cell();
c3.DataType = CellValues.String;
c3.CellValue = new CellValue("some string");
Cell c4 = new Cell();
c4.DataType = CellValues.String;
c4.CellValue = new CellValue("some car");
r2.Append(c3);
r2.Append(c4);
sd.Append(r2);
ws.Append(sd);
wsp.Worksheet = ws;
wsp.Worksheet.Save();
Sheets sheets = new Sheets();
Sheet sheet = new Sheet();
sheet.Name = "first sheet";
sheet.SheetId = 1;
sheet.Id = wbp.GetIdOfPart(wsp);
sheets.Append(sheet);
wb.Append(fv);
wb.Append(sheets);
xl.WorkbookPart.Workbook = wb;
xl.WorkbookPart.Workbook.Save();
xl.Close();
string fileName = "getdata.xlsx";
Response.Clear();
byte[] dt = ms.ToArray();
//Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
//Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));
//Response.BinaryWrite(dt);
//Response.End();
return File(dt, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "getdata.xlsx");
}
private void GenerateWorkbookStylesPart1Content(WorkbookStylesPart workbookStylesPart1)
{
Stylesheet stylesheet1 = new Stylesheet() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "x14ac x16r2" } };
stylesheet1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
stylesheet1.AddNamespaceDeclaration("x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac");
stylesheet1.AddNamespaceDeclaration("x16r2", "http://schemas.microsoft.com/office/spreadsheetml/2015/02/main");
Fonts fonts1 = new Fonts() { Count = (UInt32Value)2U, KnownFonts = true };
Font font1 = new Font();
FontSize fontSize1 = new FontSize() { Val = 11D };
Color color1 = new Color() { Theme = (UInt32Value)1U };
FontName fontName1 = new FontName() { Val = "Calibri" };
FontFamilyNumbering fontFamilyNumbering1 = new FontFamilyNumbering() { Val = 2 };
FontScheme fontScheme1 = new FontScheme() { Val = FontSchemeValues.Minor };
font1.Append(fontSize1);
font1.Append(color1);
font1.Append(fontName1);
font1.Append(fontFamilyNumbering1);
font1.Append(fontScheme1);
Font font2 = new Font();
FontSize fontSize2 = new FontSize() { Val = 11D };
Color color2 = new Color() { Theme = (UInt32Value)0U };
FontName fontName2 = new FontName() { Val = "Calibri" };
FontFamilyNumbering fontFamilyNumbering2 = new FontFamilyNumbering() { Val = 2 };
FontScheme fontScheme2 = new FontScheme() { Val = FontSchemeValues.Minor };
font2.Append(fontSize2);
font2.Append(color2);
font2.Append(fontName2);
font2.Append(fontFamilyNumbering2);
font2.Append(fontScheme2);
fonts1.Append(font1);
fonts1.Append(font2);
Fills fills1 = new Fills() { Count = (UInt32Value)3U };
Fill fill1 = new Fill();
PatternFill patternFill1 = new PatternFill() { PatternType = PatternValues.None };
fill1.Append(patternFill1);
Fill fill2 = new Fill();
PatternFill patternFill2 = new PatternFill() { PatternType = PatternValues.Gray125 };
fill2.Append(patternFill2);
Fill fill3 = new Fill();
PatternFill patternFill3 = new PatternFill() { PatternType = PatternValues.Solid };
ForegroundColor foregroundColor1 = new ForegroundColor() { Rgb = "FF0070C0" };
BackgroundColor backgroundColor1 = new BackgroundColor() { Indexed = (UInt32Value)64U };
patternFill3.Append(foregroundColor1);
patternFill3.Append(backgroundColor1);
fill3.Append(patternFill3);
fills1.Append(fill1);
fills1.Append(fill2);
fills1.Append(fill3);
Borders borders1 = new Borders() { Count = (UInt32Value)2U };
Border border1 = new Border();
LeftBorder leftBorder1 = new LeftBorder();
RightBorder rightBorder1 = new RightBorder();
TopBorder topBorder1 = new TopBorder();
BottomBorder bottomBorder1 = new BottomBorder();
DiagonalBorder diagonalBorder1 = new DiagonalBorder();
border1.Append(leftBorder1);
border1.Append(rightBorder1);
border1.Append(topBorder1);
border1.Append(bottomBorder1);
border1.Append(diagonalBorder1);
Border border2 = new Border();
LeftBorder leftBorder2 = new LeftBorder() { Style = BorderStyleValues.Double };
Color color3 = new Color() { Auto = true };
leftBorder2.Append(color3);
RightBorder rightBorder2 = new RightBorder() { Style = BorderStyleValues.Double };
Color color4 = new Color() { Auto = true };
rightBorder2.Append(color4);
TopBorder topBorder2 = new TopBorder() { Style = BorderStyleValues.Double };
Color color5 = new Color() { Auto = true };
topBorder2.Append(color5);
BottomBorder bottomBorder2 = new BottomBorder() { Style = BorderStyleValues.Double };
Color color6 = new Color() { Auto = true };
bottomBorder2.Append(color6);
DiagonalBorder diagonalBorder2 = new DiagonalBorder();
border2.Append(leftBorder2);
border2.Append(rightBorder2);
border2.Append(topBorder2);
border2.Append(bottomBorder2);
border2.Append(diagonalBorder2);
borders1.Append(border1);
borders1.Append(border2);
CellStyleFormats cellStyleFormats1 = new CellStyleFormats() { Count = (UInt32Value)1U };
CellFormat cellFormat1 = new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U };
cellStyleFormats1.Append(cellFormat1);
CellFormats cellFormats1 = new CellFormats() { Count = (UInt32Value)2U };
CellFormat cellFormat2 = new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U };
CellFormat cellFormat3 = new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)1U, FillId = (UInt32Value)2U, BorderId = (UInt32Value)1U, FormatId = (UInt32Value)0U, ApplyFont = true, ApplyFill = true, ApplyBorder = true };
cellFormats1.Append(cellFormat2);
cellFormats1.Append(cellFormat3);
CellStyles cellStyles1 = new CellStyles() { Count = (UInt32Value)1U };
CellStyle cellStyle1 = new CellStyle() { Name = "Normal", FormatId = (UInt32Value)0U, BuiltinId = (UInt32Value)0U };
cellStyles1.Append(cellStyle1);
DifferentialFormats differentialFormats1 = new DifferentialFormats() { Count = (UInt32Value)0U };
TableStyles tableStyles1 = new TableStyles() { Count = (UInt32Value)0U, DefaultTableStyle = "TableStyleMedium2", DefaultPivotStyle = "PivotStyleLight16" };
StylesheetExtensionList stylesheetExtensionList1 = new StylesheetExtensionList();
StylesheetExtension stylesheetExtension1 = new StylesheetExtension() { Uri = "{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}" };
stylesheetExtension1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main");
X14.SlicerStyles slicerStyles1 = new X14.SlicerStyles() { DefaultSlicerStyle = "SlicerStyleLight1" };
stylesheetExtension1.Append(slicerStyles1);
StylesheetExtension stylesheetExtension2 = new StylesheetExtension() { Uri = "{9260A510-F301-46a8-8635-F512D64BE5F5}" };
stylesheetExtension2.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main");
X15.TimelineStyles timelineStyles1 = new X15.TimelineStyles() { DefaultTimelineStyle = "TimeSlicerStyleLight1" };
stylesheetExtension2.Append(timelineStyles1);
stylesheetExtensionList1.Append(stylesheetExtension1);
stylesheetExtensionList1.Append(stylesheetExtension2);
stylesheet1.Append(fonts1);
stylesheet1.Append(fills1);
stylesheet1.Append(borders1);
stylesheet1.Append(cellStyleFormats1);
stylesheet1.Append(cellFormats1);
stylesheet1.Append(cellStyles1);
stylesheet1.Append(differentialFormats1);
stylesheet1.Append(tableStyles1);
stylesheet1.Append(stylesheetExtensionList1);
workbookStylesPart1.Stylesheet = stylesheet1;
}
I am using oxyplot to plot a bar chart. I wish to add an extra label in the chart. I've tried to use Textannotation but it's not showing on the chart. What is the mistake I'm making to cause the text not to appear, is it the DataPoint? Please help.
plotModel = new PlotModel
{
Title = "Daily",
LegendPlacement = LegendPlacement.Outside,
LegendPosition = LegendPosition.BottomCenter,
LegendOrientation = LegendOrientation.Horizontal,
LegendBorderThickness = 0
};
TextAnnotation txtlabel = new TextAnnotation();
txtlabel.Text = "Test";
txtlabel.TextColor = OxyColors.Red;
txtlabel.Stroke = OxyColors.Red;
txtlabel.StrokeThickness = 5;
txtlabel.FontSize = 36;
txtlabel.TextPosition = new DataPoint(21, 3.5);
plotModel.Annotations.Add(txtlabel);
string sPrevType = "";
string sCurrentType = "";
DateTime dtdate;
var sr = new ColumnSeries();
var col = new ColumnItem();
int iCount = 0;
List<decimal> lstI = new List<decimal>();
List<decimal> lstD = new List<decimal>();
List<decimal> lstS = new List<decimal>();
foreach (var itm in _dateodr)
{
dtdate = itm.date;
sCurrentType = itm.Type;
lstI.Add(itm.I_Unit);
lstD.Add(itm.D_Unit);
lstS.Add(itm.S_Unit);
if (sCurrentType != sPrevType && sPrevType != "")
{
sr = new ColumnSeries();
sr.Title = sPrevType;
sr.LabelPlacement = LabelPlacement.Outside;
sr.StrokeColor = OxyColors.Black;
sr.StrokeThickness = 1;
//sr.LabelFormatString = "{0:#,##0.00}";
plotModel.Series.Add(sr);
}
sPrevType = sCurrentType;
iCount += 1;
}
if (iCount == _dateodr.Count)
{
sr = new ColumnSeries();
sr.Title = sPrevType;
sr.LabelPlacement = LabelPlacement.Outside;
sr.StrokeColor = OxyColors.Black;
sr.StrokeThickness = 1;
//sr.LabelFormatString = "{0:#,##0.00}";
sr.FontSize = 10;
plotModel.Series.Add(sr);
}
for (int i = 0; i < iCount; i++)
{
ColumnSeries ssr = (ColumnSeries)plotModel.Series[i];
var colIm = new ColumnItem();
colIitm.Value = double.Parse(lstI[i].ToString()) / 1000;
ssr.Items.Add(colIitm);
var colDOitm = new ColumnItem();
colDitm.Value = double.Parse(lstD[i].ToString()) / 1000;
ssr.Items.Add(colDitm);
var colSitm = new ColumnItem();
colSitm.Value = double.Parse(lstS[i].ToString()) / 1000;
ssr.Items.Add(colSitm);
}
categoryaxis.Labels.Add("I");
categoryaxis.Labels.Add("Dr");
categoryaxis.Labels.Add("Sr");
switch (sUnitType)
{
case "2":
valueAxis = new LinearAxis { Position = AxisPosition.Left, MinimumPadding = 0, MaximumPadding = 0.06, AbsoluteMinimum = 0, Title = "m", Angle = 90, FontWeight = FontWeights.Bold, FontSize = 15 };
break;
case "qy":
valueAxis = new LinearAxis { Position = AxisPosition.Left, MinimumPadding = 0, MaximumPadding = 0.06, AbsoluteMinimum = 0, Title = "Qy", Angle = 90, FontWeight = FontWeights.Bold, FontSize = 15 };
break;
case "Am":
valueAxis = new LinearAxis { Position = AxisPosition.Left, MinimumPadding = 0, MaximumPadding = 0.06, AbsoluteMinimum = 0, Title = "Am", Angle = 90, FontWeight = FontWeights.Bold, FontSize = 15 };
break;
}
plotModel.Axes.Add(categoryaxis);
plotModel.Axes.Add(valueAxis);
}
PlotView plot = new PlotView
{
VerticalOptions = LayoutOptions.Fill,
HorizontalOptions = LayoutOptions.Fill,
BackgroundColor = Color.White,
Model = plotModel
};
Content = plot;
i am using ms chart to crate graph in asp.net mvc3 !
i created the graph.
Now i want to set some text on a particular datapoint. For example at (185,90)
here is my code
public ActionResult GetGraph()
{
System.Web.UI.DataVisualization.Charting.Chart Chart2 = new System.Web.UI.DataVisualization.Charting.Chart();
Chart2.Width = 800;
Chart2.Height = 600;
var series = new Series();
series.ChartArea = "ca1";
var area = new ChartArea("ca1");
area.Area3DStyle.Enable3D = false;
area.AxisX.Title = "Height";
area.AxisX.IsStartedFromZero = true;
area.AxisX.Maximum = 200;
area.AxisX.Minimum = 110;
//area.AxisX.Interval = 10;
area.AxisY.Minimum = 10;
area.AxisY.Maximum = 110;
area.AxisY.Interval = 10;
area.AxisY.TitleFont = new Font("Arial,Helvetica,sans-serif",
10F, FontStyle.Regular);
area.AxisX.TitleFont = new Font("Arial,Helvetica,sans-serif",
10F, FontStyle.Regular);
area.AxisY.Title = "Weight";
// area.InnerPlotPosition.Height = 10;
area.AxisX.IsLabelAutoFit = false;
area.AxisY.IsLabelAutoFit = false;
new Font("Arial,Helvetica,sans-serif",
10F, FontStyle.Regular);
area.AxisY.LabelStyle.Font =
new Font("Arial,Helvetica,sans-serif",
10F, FontStyle.Regular);
area.AxisY.LineColor = Color.FromArgb(64, 64, 64, 64);
area.AxisX.LineColor = Color.FromArgb(64, 64, 64, 64);
area.AxisY.MajorGrid.LineColor = Color.FromArgb(64, 64, 64, 64);
area.AxisX.MajorGrid.LineColor = Color.FromArgb(64, 64, 64, 64);
area.Position.Auto = false;
area.Position.X = 1;
area.Position.Y = 1;
area.Position.Width = 100;
area.Position.Height = 100;
area.InnerPlotPosition.X = 10;
area.InnerPlotPosition.Y = 5;
area.InnerPlotPosition.Width = 85;
area.InnerPlotPosition.Height = 85;
Chart2.ChartAreas.Add(area);
Chart2.ChartAreas.Add("curve 15").BackColor = System.Drawing.Color.FromArgb(64, System.Drawing.Color.White);
Chart2.Series.Add("curve 15").ChartType = SeriesChartType.Line;
Chart2.Series.Add("curve 18.5").ChartType = SeriesChartType.Line;
Chart2.Series.Add("curve22").ChartType = SeriesChartType.Line;
Chart2.Series.Add("curve25").ChartType = SeriesChartType.Line;
Chart2.Series.Add("curve30").ChartType = SeriesChartType.Line;
Chart2.Series.Add("bmi30").ChartType = SeriesChartType.FastPoint;
Chart2.Series["bmi30"].Points.AddXY(185,96);
Chart2.Series["bmi30"].IsValueShownAsLabel = true;
Chart2.Series["bmi30"].Label = "BMI";
Chart2.Series["curve 15"].Color = Color.Blue;
Chart2.Series["curve 15"].BorderWidth = 2;
Chart2.Series["curve 15"].Points.AddXY(120, 21);
Chart2.Series["curve 15"].Points.AddXY(130, 25);
Chart2.Series["curve 15"].Points.AddXY(140, 27);
Chart2.Series["curve 15"].Points.AddXY(150, 32.5);
Chart2.Series["curve 15"].Points.AddXY(160, 37.5);
Chart2.Series["curve 15"].Points.AddXY(170, 42);
Chart2.Series["curve 15"].Points.AddXY(185, 48);
Chart2.Series["curve 15"].Points.Last().AxisLabel = "lllcc";
Chart2.Series["curve 18.5"].Color = Color.Red;
Chart2.Series["curve 18.5"].BorderWidth = 2;
Chart2.Series["curve 18.5"].Points.AddXY(120, 26);
Chart2.Series["curve 18.5"].Points.AddXY(130, 31);
Chart2.Series["curve 18.5"].Points.AddXY(140, 36);
Chart2.Series["curve 18.5"].Points.AddXY(150, 41);
Chart2.Series["curve 18.5"].Points.AddXY(160, 48);
Chart2.Series["curve 18.5"].Points.AddXY(170, 50.5);
Chart2.Series["curve 18.5"].Points.AddXY(185, 63);
Chart2.Series["curve22"].Color = Color.Chocolate;
Chart2.Series["curve22"].BorderWidth = 2;
Chart2.Series["curve22"].Points.AddXY(120, 30.5);
Chart2.Series["curve22"].Points.AddXY(130,36);
Chart2.Series["curve22"].Points.AddXY(140, 42);
Chart2.Series["curve22"].Points.AddXY(150,49);
Chart2.Series["curve22"].Points.AddXY(160, 51);
Chart2.Series["curve22"].Points.AddXY(170, 61);
Chart2.Series["curve22"].Points.AddXY(185,71);
Chart2.Series["curve25"].Color = Color.Yellow;
Chart2.Series["curve25"].BorderWidth = 2;
Chart2.Series["curve25"].Points.AddXY(120,36);
Chart2.Series["curve25"].Points.AddXY(130, 41);
Chart2.Series["curve25"].Points.AddXY(140,48.5);
Chart2.Series["curve25"].Points.AddXY(150,56);
Chart2.Series["curve25"].Points.AddXY(160,58);
Chart2.Series["curve25"].Points.AddXY(170,71);
Chart2.Series["curve25"].Points.AddXY(185,81);
Chart2.Series["curve30"].Color = Color.Green;
Chart2.Series["curve30"].BorderWidth = 2;
Chart2.Series["curve30"].Points.AddXY(120, 42);
Chart2.Series["curve30"].Points.AddXY(130, 50);
Chart2.Series["curve30"].Points.AddXY(140, 58);
Chart2.Series["curve30"].Points.AddXY(150, 66);
Chart2.Series["curve30"].Points.AddXY(160, 76);
Chart2.Series["curve30"].Points.AddXY(170, 85);
Chart2.Series["curve30"].Points.AddXY(185, 96);
Chart2.BackColor = Color.Transparent;
MemoryStream imageStream = new MemoryStream();
Chart2.SaveImage(imageStream, ChartImageFormat.Png);
Chart2.TextAntiAliasingQuality = TextAntiAliasingQuality.SystemDefault;
Response.ContentType = "image/png";
imageStream.WriteTo(Response.OutputStream);
return PartialView("_GetGraph");
}
i tried using the link
Adding text , image to asp.net chart control
but the label is not showing.
also i want to start x with 0,120,130,...
and y axes to 0,20,30
is it possible? any help appericiated
You should first create a datapoint and then add it to the series. For example:
DataPoint dp = new DataPoint();
dp4.Font = dp_font;
dp4.XValue = 185;
dp4.SetValueY(90);
dp4.Label = "Label text";
Series["bmi30"].Points.Add(dp)
I'm using MvcxGridView to bind a DataTable model and I have a problem with a DataColumn with datatype System.Byte[].
When I view data, gridview does not show a value and only displays System.Byte[]. I want the GridView to display a picture in that column.
When I save data, I get this message:
Invalid cast from 'System.String' to 'System.Byte[]'
How can I solve these problems?
Here is my code in view:
#using System.Data;
#model TestPA6MVC.Models.EntityModelForViewDataSettingGrid
#functions{
MVCxGridViewCommandColumn CreateCommandColumn(string AllowEdit,string AllowAdd)
{
MVCxGridViewCommandColumn column = new MVCxGridViewCommandColumn();
column.Visible = true;
column.NewButton.Visible = (AllowAdd.ToLower()=="true")?true:false;
column.DeleteButton.Visible = (AllowEdit.ToLower() == "true") ? true : false; ;
//column.EditButton.Visible = true;
return column;
}
}
#{
var grid = Html.DevExpress().GridView(
settings => {
settings.Name = "gvEditing";
settings.CallbackRouteValues = new {
Controller = "Home", Action = "GridViewPartial",
ViewName = Model.ViewName,
PrimaryKeyCollection = Model.PrimaryKeyCollection,
TableEditorList = Model.TableEditorList,
ColumnComboBoxCollection = Model.ColumnComboBoxCollection,
ColumnReadOnlyCollection = Model.ColumnReadOnlyCollection,
ColumnHideCollection = Model.ColumnHideCollection,
ParamNameCollection = Model.ParamNameCollection,
DataForParamCollection = Model.DataForParamCollection,
ParamTypeCollection = Model.ParamTypeCollection,
AllowAdd = Model.AllowAdd,
AllowEdit = Model.AllowEdit
};
settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "Home", Action = "GridViewPartialAddNew", ViewName = Model.ViewName };
settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "Home", Action = "GridViewPartialUpdate", ViewName = Model.ViewName };
settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "Home", Action = "GridViewPartialDelete", ViewName = Model.ViewName };
settings.SettingsEditing.BatchUpdateRouteValues = new {
Controller = "Home", Action = "BatchEditingUpdateModel",
ViewName = Model.ViewName,
PrimaryKeyCollection = Model.PrimaryKeyCollection,
TableEditorList = Model.TableEditorList,
ColumnComboBoxCollection = Model.ColumnComboBoxCollection,
ColumnReadOnlyCollection = Model.ColumnReadOnlyCollection,
ColumnHideCollection = Model.ColumnHideCollection,
ParamNameCollection = Model.ParamNameCollection,
DataForParamCollection = Model.DataForParamCollection,
ParamTypeCollection = Model.ParamTypeCollection,
AllowAdd = Model.AllowAdd,
AllowEdit = Model.AllowEdit
};
if (Model.AllowEdit.ToLower() == "true")
{
settings.SettingsEditing.Mode = GridViewEditingMode.Batch;//Kieu view chinh sua
}
else { settings.SettingsEditing.Mode = GridViewEditingMode.PopupEditForm; }
settings.SettingsBehavior.ConfirmDelete = true;//Cho phep hien thi thong bao xac nhan
settings.SettingsBehavior.ColumnResizeMode = ColumnResizeMode.Control;//Cho phep chinh sua do rong cot
settings.Width = 800;//Chieu rong cua gridview
settings.Settings.HorizontalScrollBarMode = ScrollBarMode.Auto;
settings.SettingsPager.Mode = GridViewPagerMode.ShowPager;
settings.SettingsPager.PageSize = 50;
settings.Settings.VerticalScrollableHeight = 300;
settings.Settings.VerticalScrollBarMode = ScrollBarMode.Auto;
settings.SettingsPager.Visible = true;
settings.Settings.ShowGroupPanel = true;
settings.Settings.ShowFilterRow = true;
settings.Settings.ShowHeaderFilterButton = true;//Hien thi bo loc cho column
//Tao cot gia de tranh tinh trang hien thi lai cac Column an khi Callback
MVCxGridViewColumn fakeco = new MVCxGridViewColumn();
fakeco.Visible = false;
fakeco.Width = 0;
fakeco.EditFormSettings.Visible = DefaultBoolean.False;
settings.Columns.Add(fakeco);
settings.SettingsBehavior.AllowSelectByRowClick = true;
settings.DataBound = (sender, e) =>
{
//Build Column Tool Automatic
((MVCxGridView)sender).Columns.Insert(0, CreateCommandColumn(Model.AllowEdit,Model.AllowAdd));
//Add custom Column
foreach (var child in Model.ModelForDisplayColumnList)
{
MVCxGridViewColumn dc = new MVCxGridViewColumn();
dc.Caption = child.Caption;
dc.FieldName = child.ColumnName;
if(child.IsHidden)//Neu de an hoan toan se khong lay duoc du lieu da chinh sua
{ dc.Width = 0; }
//dc.Visible = !child.IsHidden;
dc.ReadOnly = child.IsReadOnly;
switch (child.DataType)
{
case "datetime":
dc.ColumnType = MVCxGridViewColumnType.DateEdit;
var DateEditProperties = dc.PropertiesEdit as DateEditProperties;
DateEditProperties.DisplayFormatString = "dd/MM/yyyy hh:mm tt";
//Cho phep chinh ngay, gio
DateEditProperties.UseMaskBehavior = true;
//Dinh dang hien thi khi chinh sua
DateEditProperties.EditFormat = EditFormat.Custom;
DateEditProperties.EditFormatString = "dd/MM/yyyy hh:mm tt";
DateEditProperties.TimeSectionProperties.Visible = true;//Hien khung chinh gio
break;
case "combobox":
dc.ColumnType = MVCxGridViewColumnType.ComboBox;
var DropDownEditProperties = dc.PropertiesEdit as ComboBoxProperties;
DropDownEditProperties.DataSource = child.DataSourceForComboBoxColumn;
DropDownEditProperties.ValueField = child.DataSourceForComboBoxColumn.Columns[0].ColumnName;
DropDownEditProperties.TextFormatString = "{0}";
foreach (DataColumn childcolumn in child.DataSourceForComboBoxColumn.Columns)
{
DropDownEditProperties.Columns.Add(childcolumn.ColumnName, childcolumn.ColumnName);
}
break;
case "boolean":
case "bit":
dc.ColumnType = MVCxGridViewColumnType.CheckBox;
break;
case "byte[]":
dc.ColumnType = MVCxGridViewColumnType.BinaryImage;
//var ImageEditProperties = dc.PropertiesEdit as BinaryImageEditProperties;
//ImageEditProperties.ImageWidth = 50;
//ImageEditProperties.ImageHeight = 50;
break;
//case "string":
// dc.ColumnType = MVCxGridViewColumnType.ComboBox;
// var ComboBoxEditProperties = dc.PropertiesEdit as ComboBoxProperties;
// ComboBoxEditProperties.DataSource = ModelForDisplayColumnList;
// ComboBoxEditProperties.TextField = "DataType";
// ComboBoxEditProperties.ValueField = "Caption";
// break;
}
((MVCxGridView)sender).Columns.Add(dc);
}
};
settings.KeyFieldName = Model.PrimaryKeyCollection;
});
if (ViewData["EditError"] != null){
grid.SetEditErrorText((string)ViewData["EditError"]);
}
}
#grid.Bind(Model.DataSourceForGrid).GetHtml()
Hello everyone i am working on a project which requires me to export some data to excel on a button click using open xml.Here is the class i am using for exporting to excel:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Drawing.Spreadsheet;
using _14junexcel.Account;
namespace _14junexcel
{
public class CreateExcelOpen
{
public void BuildWorkbook1(string filename)
{
string sFile = #"D:\\ExcelOpenXmlWithImageAndStyles.xlsx";
if (File.Exists(sFile))
{
File.Delete(sFile);
}
BuildWorkbook(sFile);
}
private static void BuildWorkbook(string filename)
{
try
{
using (SpreadsheetDocument xl = SpreadsheetDocument.Create(filename, SpreadsheetDocumentType.Workbook))
{
WorkbookPart wbp = xl.AddWorkbookPart();
WorksheetPart wsp = wbp.AddNewPart<WorksheetPart>();
Workbook wb = new Workbook();
FileVersion fv = new FileVersion();
fv.ApplicationName = "Microsoft Office Excel";
Worksheet ws = new Worksheet();
SheetData sd = new SheetData();
WorkbookStylesPart wbsp = wbp.AddNewPart<WorkbookStylesPart>();
wbsp.Stylesheet = CreateStylesheet();
wbsp.Stylesheet.Save();
string sImagePath = #"C:\\Users\\Public\\Pictures\\Sample Pictures\\Jellyfish.jpg";
DrawingsPart dp = wsp.AddNewPart<DrawingsPart>();
ImagePart imgp = dp.AddImagePart(ImagePartType.Png, wsp.GetIdOfPart(dp));
using (FileStream fs = new FileStream(sImagePath, FileMode.Open))
{
imgp.FeedData(fs);
}
NonVisualDrawingProperties nvdp = new NonVisualDrawingProperties();
nvdp.Id = 1025;
nvdp.Name = "Picture 1";
nvdp.Description = "polymathlogo";
DocumentFormat.OpenXml.Drawing.PictureLocks picLocks = new DocumentFormat.OpenXml.Drawing.PictureLocks();
picLocks.NoChangeAspect = true;
picLocks.NoChangeArrowheads = true;
NonVisualPictureDrawingProperties nvpdp = new NonVisualPictureDrawingProperties();
nvpdp.PictureLocks = picLocks;
NonVisualPictureProperties nvpp = new NonVisualPictureProperties();
nvpp.NonVisualDrawingProperties = nvdp;
nvpp.NonVisualPictureDrawingProperties = nvpdp;
DocumentFormat.OpenXml.Drawing.Stretch stretch = new DocumentFormat.OpenXml.Drawing.Stretch();
stretch.FillRectangle = new DocumentFormat.OpenXml.Drawing.FillRectangle();
BlipFill blipFill = new BlipFill();
DocumentFormat.OpenXml.Drawing.Blip blip = new DocumentFormat.OpenXml.Drawing.Blip();
blip.Embed = dp.GetIdOfPart(imgp);
blip.CompressionState = DocumentFormat.OpenXml.Drawing.BlipCompressionValues.Print;
blipFill.Blip = blip;
blipFill.SourceRectangle = new DocumentFormat.OpenXml.Drawing.SourceRectangle();
blipFill.Append(stretch);
DocumentFormat.OpenXml.Drawing.Transform2D t2d = new DocumentFormat.OpenXml.Drawing.Transform2D();
DocumentFormat.OpenXml.Drawing.Offset offset = new DocumentFormat.OpenXml.Drawing.Offset();
offset.X = 0;
offset.Y = 0;
t2d.Offset = offset;
Bitmap bm = new Bitmap(sImagePath);
//http://en.wikipedia.org/wiki/English_Metric_Unit#DrawingML
//http://stackoverflow.com/questions/1341930/pixel-to-centimeter
//http://stackoverflow.com/questions/139655/how-to-convert-pixels-to-points-px-to-pt-in-net-c
DocumentFormat.OpenXml.Drawing.Extents extents = new DocumentFormat.OpenXml.Drawing.Extents();
extents.Cx = (long)bm.Width * (long)((float)0 / bm.HorizontalResolution);
extents.Cy = (long)bm.Height * (long)((float)0 / bm.VerticalResolution);
bm.Dispose();
t2d.Extents = extents;
ShapeProperties sp = new ShapeProperties();
sp.BlackWhiteMode = DocumentFormat.OpenXml.Drawing.BlackWhiteModeValues.Auto;
sp.Transform2D = t2d;
DocumentFormat.OpenXml.Drawing.PresetGeometry prstGeom = new DocumentFormat.OpenXml.Drawing.PresetGeometry();
prstGeom.Preset = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle;
prstGeom.AdjustValueList = new DocumentFormat.OpenXml.Drawing.AdjustValueList();
sp.Append(prstGeom);
sp.Append(new DocumentFormat.OpenXml.Drawing.NoFill());
DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture picture = new DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture();
picture.NonVisualPictureProperties = nvpp;
picture.BlipFill = blipFill;
picture.ShapeProperties = sp;
Position pos = new Position();
pos.X = 0;
pos.Y = 0;
Extent ext = new Extent();
ext.Cx = extents.Cx;
ext.Cy = extents.Cy;
AbsoluteAnchor anchor = new AbsoluteAnchor();
anchor.Position = pos;
anchor.Extent = ext;
anchor.Append(picture);
anchor.Append(new ClientData());
WorksheetDrawing wsd = new WorksheetDrawing();
wsd.Append(anchor);
Drawing drawing = new Drawing();
drawing.Id = dp.GetIdOfPart(imgp);
wsd.Save(dp);
UInt32 index;
Random rand = new Random();
sd.Append(CreateHeader(2));
sd.Append(CreateColumnHeader(4));
for (index = 5; index < 6; ++index)
{
sd.Append(CreateContent(index, ref rand));
}
ws.Append(sd);
ws.Append(drawing);
wsp.Worksheet = ws;
wsp.Worksheet.Save();
Sheets sheets = new Sheets();
Sheet sheet = new Sheet();
sheet.Name = "Sheet1";
sheet.SheetId = 1;
sheet.Id = wbp.GetIdOfPart(wsp);
sheets.Append(sheet);
wb.Append(fv);
wb.Append(sheets);
xl.WorkbookPart.Workbook = wb;
xl.WorkbookPart.Workbook.Save();
//xl.WorkbookPart.Workbook.Save();
xl.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
Console.ReadLine();
}
}
private static Stylesheet CreateStylesheet()
{
Stylesheet ss = new Stylesheet();
Fonts fts = new Fonts();
DocumentFormat.OpenXml.Spreadsheet.Font ft = new DocumentFormat.OpenXml.Spreadsheet.Font();
FontName ftn = new FontName();
ftn.Val = StringValue.FromString("Calibri");
FontSize ftsz = new FontSize();
ftsz.Val = DoubleValue.FromDouble(11);
ft.FontName = ftn;
ft.FontSize = ftsz;
fts.Append(ft);
ft = new DocumentFormat.OpenXml.Spreadsheet.Font();
ftn = new FontName();
ftn.Val = StringValue.FromString("Palatino Linotype");
ftsz = new FontSize();
ftsz.Val = DoubleValue.FromDouble(18);
ft.FontName = ftn;
ft.FontSize = ftsz;
fts.Append(ft);
fts.Count = UInt32Value.FromUInt32((uint)fts.ChildElements.Count);
Fills fills = new Fills();
Fill fill;
PatternFill patternFill;
fill = new Fill();
patternFill = new PatternFill();
patternFill.PatternType = PatternValues.None;
fill.PatternFill = patternFill;
fills.Append(fill);
fill = new Fill();
patternFill = new PatternFill();
patternFill.PatternType = PatternValues.Gray125;
fill.PatternFill = patternFill;
fills.Append(fill);
fill = new Fill();
patternFill = new PatternFill();
patternFill.PatternType = PatternValues.Solid;
patternFill.ForegroundColor = new ForegroundColor();
patternFill.ForegroundColor.Rgb = HexBinaryValue.FromString("00ff9728");
patternFill.BackgroundColor = new BackgroundColor();
patternFill.BackgroundColor.Rgb = patternFill.ForegroundColor.Rgb;
fill.PatternFill = patternFill;
fills.Append(fill);
fills.Count = UInt32Value.FromUInt32((uint)fills.ChildElements.Count);
Borders borders = new Borders();
Border border = new Border();
border.LeftBorder = new LeftBorder();
border.RightBorder = new RightBorder();
border.TopBorder = new TopBorder();
border.BottomBorder = new BottomBorder();
border.DiagonalBorder = new DiagonalBorder();
borders.Append(border);
border = new Border();
border.LeftBorder = new LeftBorder();
border.LeftBorder.Style = BorderStyleValues.Thin;
border.RightBorder = new RightBorder();
border.RightBorder.Style = BorderStyleValues.Thin;
border.TopBorder = new TopBorder();
border.TopBorder.Style = BorderStyleValues.Thin;
border.BottomBorder = new BottomBorder();
border.BottomBorder.Style = BorderStyleValues.Thin;
border.DiagonalBorder = new DiagonalBorder();
borders.Append(border);
borders.Count = UInt32Value.FromUInt32((uint)borders.ChildElements.Count);
CellStyleFormats csfs = new CellStyleFormats();
CellFormat cf = new CellFormat();
cf.NumberFormatId = 0;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 1;
csfs.Append(cf);
csfs.Count = UInt32Value.FromUInt32((uint)csfs.ChildElements.Count);
uint iExcelIndex = 164;
NumberingFormats nfs = new NumberingFormats();
CellFormats cfs = new CellFormats();
cf = new CellFormat();
cf.NumberFormatId = 0;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 0;
cf.FormatId = 0;
cfs.Append(cf);
NumberingFormat nfDateTime = new NumberingFormat();
nfDateTime.NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++);
nfDateTime.FormatCode = StringValue.FromString("dd/mm/yyyy hh:mm:ss");
nfs.Append(nfDateTime);
NumberingFormat nf4decimal = new NumberingFormat();
nf4decimal.NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++);
nf4decimal.FormatCode = StringValue.FromString("#,##0.0000");
nfs.Append(nf4decimal);
// #,##0.00 is also Excel style index 4
NumberingFormat nf2decimal = new NumberingFormat();
nf2decimal.NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++);
nf2decimal.FormatCode = StringValue.FromString("#,##0.00");
nfs.Append(nf2decimal);
// # is also Excel style index 49
NumberingFormat nfForcedText = new NumberingFormat();
nfForcedText.NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++);
nfForcedText.FormatCode = StringValue.FromString("#");
nfs.Append(nfForcedText);
//Alignment
Alignment align = new Alignment(){Horizontal = HorizontalAlignmentValues.General,Vertical=VerticalAlignmentValues.Center};
//wraptext
// Alignment align1 = new Alignment(){Horizontal=HorizontalAlignmentValues.CenterContinuous,Vertical=VerticalAlignmentValues.Center};
// index 1
cf = new CellFormat();
cf.NumberFormatId = nfDateTime.NumberFormatId;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId = 0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
// index 2
cf = new CellFormat();
cf.NumberFormatId = nf4decimal.NumberFormatId;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId = 0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
// index 3
cf = new CellFormat();
cf.NumberFormatId = nf2decimal.NumberFormatId;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId = 0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
// index 4
cf = new CellFormat();
cf.NumberFormatId = nfForcedText.NumberFormatId;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId = 0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
// index 5
// Header text
cf = new CellFormat();
cf.NumberFormatId = nfForcedText.NumberFormatId;
cf.FontId = 1;
cf.FillId = 0;
cf.BorderId = 0;
cf.FormatId = 0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
// index 6
// column text
cf = new CellFormat();
cf.NumberFormatId = nfForcedText.NumberFormatId;
cf.FontId = 1;
cf.FillId = 1;
cf.BorderId = 1;
cf.FormatId = 1;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
// index 7
// coloured 2 decimal text
cf = new CellFormat();
cf.NumberFormatId = nf2decimal.NumberFormatId;
cf.FontId = 0;
//cf.FillId = 2;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId =0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
//cf.Append(align);
cf.Append(align);
// index 8
// coloured column text
cf = new CellFormat();
cf.NumberFormatId = nfForcedText.NumberFormatId;
cf.FontId = 0;
//cf.FillId = 2;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId = 0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
nfs.Count = UInt32Value.FromUInt32((uint)nfs.ChildElements.Count);
cfs.Count = UInt32Value.FromUInt32((uint)cfs.ChildElements.Count);
ss.Append(nfs);
ss.Append(fts);
ss.Append(fills);
ss.Append(borders);
ss.Append(csfs);
ss.Append(cfs);
CellStyles css = new CellStyles();
CellStyle cs = new CellStyle();
cs.Name = StringValue.FromString("Normal");
cs.FormatId = 0;
cs.BuiltinId = 0;
css.Append(cs);
css.Count = UInt32Value.FromUInt32((uint)css.ChildElements.Count);
ss.Append(css);
DifferentialFormats dfs = new DifferentialFormats();
dfs.Count = 0;
ss.Append(dfs);
TableStyles tss = new TableStyles();
tss.Count = 0;
tss.DefaultTableStyle = StringValue.FromString("TableStyleMedium9");
tss.DefaultPivotStyle = StringValue.FromString("PivotStyleLight16");
ss.Append(tss);
return ss;
}
private static Row CreateHeader(UInt32 index)
{
Row r = new Row();
r.RowIndex = index;
Cell c = new Cell();
c.DataType = CellValues.String;
c.StyleIndex = 5;
c.CellReference = "A" + index.ToString();
c.CellValue = new CellValue("REPORT");
r.Append(c);
return r;
}
private static Row CreateColumnHeader(UInt32 index)
{
Row r = new Row();
r.RowIndex = index;
Cell c;
c = new Cell();
c.DataType = CellValues.String;
c.StyleIndex = 7;
c.CellReference = "A" + index.ToString();
c.CellValue = new CellValue("Retail Customer Group");
r.Append(c);
c = new Cell();
c.DataType = CellValues.String;
c.StyleIndex = 7;
c.CellReference = "B" + index.ToString();
c.CellValue = new CellValue("Product Promotion Group");
r.Append(c);
return r;
}
private static Row CreateContent(UInt32 index, ref Random rd)
{
Row r = new Row();
r.RowIndex = index;
Cell c;
c = new Cell();
c.StyleIndex = 7;
c.CellReference = "A" + index.ToString();
//c.CellValue = new CellValue(rd.Next(1000000000).ToString());
c.CellValue = new CellValue("12334");
r.Append(c);
DateTime dtEpoch = new DateTime(1900, 1, 1, 0, 0, 0, 0);
DateTime dt = dtEpoch.AddDays(rd.NextDouble() * 100000.0);
TimeSpan ts = dt - dtEpoch;
double fExcelDateTime;
// Excel has "bug" of treating 29 Feb 1900 as valid
// 29 Feb 1900 is 59 days after 1 Jan 1900, so just skip to 1 Mar 1900
if (ts.Days >= 59)
{
fExcelDateTime = ts.TotalDays + 2.0;
}
else
{
fExcelDateTime = ts.TotalDays + 1.0;
}
c = new Cell();
c.StyleIndex = 7;
c.CellReference = "B" + index.ToString();
c.CellValue = new CellValue("124515");
//c.CellValue = new CellValue(fExcelDateTime.ToString());
r.Append(c);
return r;
}
}
}
and this is the function for button click :
protected void Button1_Click(object sender, EventArgs e)
{
string qwe = TextBox1.Text;
string ert = TextBox2.Text;
string filename = #"D:\\ExcelOpenXmlWithImageAndStyles.xlsx";
CreateExcelOpen exp = new CreateExcelOpen();
exp.BuildWorkbook1(filename);
}
here are my requirements:
1.I need to pass the values of two textboxes to the two cells(which now contain values 12334 and 124515).
2. The heading column does not adjust itself to accomodate the values which i have provided(Retail customer group etc).Please suggest the
modifications required in this class to enable the autofit.
Thank you.
In Your CreateContent method you have hard coded values like:
c.CellValue = new CellValue("12334");
change it with values of text boxes that you want to show.
for setting width of headers, you will have to add columns along with Cells as you need columns to define the width, following article will be of some help for you:
http://catalog.codeproject.com/script/Articles/ArticleVersion.aspx?aid=371203&av=543408
I wrote my own export to Excel writer. It is fast and allows for substantial formatting of the cells. You can review it at
https://openxmlexporttoexcel.codeplex.com/
I hope it helps.
I've spent a lot of time googling OpenXml related questions.
I finally found a solution to my problems by combining OpenXml features with Excel VBA.
So,
I have Excel - macro enabled file (xlsm) as template for my project.
Whatever logic is hard to implement in OpenXml I moved to VBA.
For AutoFit for example it is as easy as:
Sub Workbook_Open()
ActiveSheet.Columns.AutoFit
End Sub
Hope it may help.