I am creating Excel using DocumentFormat.OpenXml in ASP.Net.
Can anybody have idea how can create Multiple worksheet in Excel.
For ex. Sheet1, Sheet2, Sheet3...... sheetn
Try the following method:
/// <summary>
/// Add a blank worksheet to the workbook
/// </summary>
/// <param name="workbookPart">Wookbook part</param>
public static void InsertBlankWorksheet(WorkbookPart workbookPart)
{
// Add a blank WorksheetPart.
WorksheetPart newWorksheetPart = workbookPart.AddNewPart<WorksheetPart>();
// Create the new worksheet
Worksheet worksheet = new Worksheet();
worksheet.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
SheetDimension sheetDimension1 = new SheetDimension() { Reference = "A1" };
SheetViews sheetViews1 = new SheetViews();
SheetView sheetView1 = new SheetView() { TabSelected = true, WorkbookViewId = (UInt32Value)0U };
sheetViews1.Append(sheetView1);
SheetFormatProperties sheetFormatProperties1 = new SheetFormatProperties() { DefaultRowHeight = 15D };
SheetData sheetData1 = new SheetData();
PageMargins pageMargins1 = new PageMargins() { Left = 0.7D, Right = 0.7D, Top = 0.75D, Bottom = 0.75D, Header = 0.3D, Footer = 0.3D };
PageSetup pageSetup1 = new PageSetup() { Orientation = OrientationValues.Portrait, Id = "rId1" };
worksheet.Append(sheetDimension1);
worksheet.Append(sheetViews1);
worksheet.Append(sheetFormatProperties1);
worksheet.Append(sheetData1);
worksheet.Append(pageMargins1);
worksheet.Append(pageSetup1);
newWorksheetPart.Worksheet = worksheet;
newWorksheetPart.Worksheet.Save();
Sheets sheets = workbookPart.Workbook.GetFirstChild<Sheets>();
string relationshipId = workbookPart.GetIdOfPart(newWorksheetPart);
// Get a unique ID for the new worksheet.
uint sheetId = 1;
if (sheets.Elements<Sheet>().Count() > 0)
{
sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
}
// Give the new worksheet a name.
string sheetName = "Sheet" + sheetId;
// Append the new worksheet and associate it with the workbook.
Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
sheets.Append(sheet);
workbookPart.Workbook.Save();
}
EDIT
Here is the class that contains the method:
public static class ExcelHelpers
{
public static void InsertBlankWorksheet(WorkbookPart workbookPart)
{...}
}
Open up your excel document like this and call the method:
public static void Export(string document)
{
using (SpreadsheetDocument doc = SpreadsheetDocument.Open(document, true))
{
ExcelHelpers.InsertBlankWorksheet(doc.WorkbookPart);
}
}
Related
I am trying to separate certain items in a file into a different file. When I use errorgrades.println it does not work, but when I print it into the console, it does. What am I doing wrong?
PrintWriter errorgrade = null;
try{
Scanner in = new Scanner(System.in);
System.out.println("Enter name of input file:");
String input = in.nextLine();
File ErrorGradesFile = new File("src\\ErrorGradesFile.txt");
File FinalGradesFile = new File("src\\FinalGradesFile.txt");
File RawGradesFile = new File("src\\"+input);
Scanner in2 = new Scanner(RawGradesFile);
finalgrade = new PrintWriter(FinalGradesFile);
errorgrade = new PrintWriter(ErrorGradesFile);
String line = "";
while(in2.hasNextLine()){
String student = in2.nextLine();
String[] one = student.split(",");
if(one[1].equals(" ")){
System.out.println(student);
errorgrade.println(student);
}
else {
finalgrade.println("helo");
}
finalgrade.close();
errorgrade.close();
}
I have implemented the code below, all headers and data are added without any problem. If he wants to block the possibility of editing individual fields or columns in the excel file that is downloaded by the user, then there is a problem, because nothing is blocked
i use for freeze columns/rows, but when i export file and i open file i can edit any fields
worksheet.SheetView.Freeze(1,3);
[HttpGet]
public IActionResult ExportAsExcel()
{
IEnumerable<Employee> employees = this.repo.GetAll<Employee>();
List<EmployeeDTO> employeeDTO = this._mapper.Map<List<EmployeeDTO>>(employees);
using (var workbook = new XLWorkbook())
{
var woorksheet = workbook.Worksheets.Add("Sheet1");
var currentRow = 1;
woorksheet.Cell(currentRow, 1).Value = "ID";
woorksheet.Cell(currentRow, 2).Value = "name";
foreach (var empDtos in employeeDTO)
{
currentRow++;
woorksheet.Cell(currentRow, 1).Value = empDtos.EmployeeId;
woorksheet.Cell(currentRow, 2).Value = empDtos.Name;
}
using (var stream = new MemoryStream())
{
workbook.SaveAs(stream);
var content = stream.ToArray();
return File(
content,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"Employee.xlsx"
);
}
}
}
`loadconfig.SourceUris.Add(#"gs:\\planar-fulcrum-837\leadload-ip\01-
02-2013");`
Null object reference set to instance of an object
Here is the working sample for loading CSV file from cloud storage into Google Big Query.
Update variables such as "ServiceAccountEmail, KeyFileName, KeySecret, ProjectID, Dataset name and etc..
Add your table schema into this variable
TableSchema Schema = new TableSchema();
Here i am using single file loading, you can add N number of CSV file into this variable
System.Collections.Generic.IList<string> URIs = newSystem.Collections.Generic.List<string>();
URIs.Add(filePath);
Use this below code modify & work with it. Have a great day. (This solution i have found working more than 3 days).
using Google.Apis.Auth.OAuth2;
using System.IO;
using System.Threading;
using Google.Apis.Bigquery.v2;
using Google.Apis.Bigquery.v2.Data;
using System.Data;
using Google.Apis.Services;
using System;
using System.Security.Cryptography.X509Certificates;
namespace GoogleBigQuery
{
public class Class1
{
private static void Main()
{
try
{
String serviceAccountEmail = "SERVICE ACCOUNT EMAIL";
var certificate = new X509Certificate2(#"KEY FILE NAME & PATH", "KEY SECRET", X509KeyStorageFlags.Exportable);
// SYNTAX: var certificate=new X509Certificate2(KEY FILE PATH+NAME (Here it resides in Bin\Debug folder so only name is enough), SECRET KEY, X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { BigqueryService.Scope.Bigquery, BigqueryService.Scope.BigqueryInsertdata, BigqueryService.Scope.CloudPlatform, BigqueryService.Scope.DevstorageFullControl }
}.FromCertificate(certificate));
// Create and initialize the Bigquery service. Use the Project Name value
// from the New Project window for the ApplicationName variable.
BigqueryService Service = new BigqueryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "APPLICATION NAME"
});
TableSchema Schema = new TableSchema();
TableFieldSchema F1 = new TableFieldSchema();
F1.Name = "COLUMN NAME";
F1.Type = "STRING";
F1.Mode = "REQUIRED";
TableFieldSchema F2 = new TableFieldSchema();
F1.Name = "COLUMN NAME";
F1.Type = "INTEGER";
F1.Mode = "NULLABLE";
//Add N number of fields as per your needs
System.Collections.Generic.IList<TableFieldSchema> FS = new System.Collections.Generic.List<TableFieldSchema>();
FS.Add(F1);
FS.Add(F2);
Schema.Fields = FS;
JobReference JR = JobUpload("PROJECT ID", "DATASET NAME", "TABLE NAME", #"gs://BUCKET NAME/FILENAME", Schema, "CREATE_IF_NEEDED", "WRITE_APPEND", '|', Service);
//SYNTAX JobReference JR = JobUpload(PROJECT ID, DATASET NAME, TABLE NAME, FULL PATH OF CSV FILE,FILENAME IN CLOUD STORAGE, TABLE SCHEMA, CREATE DISPOSITION, DELIMITER, BIGQUERY SERVICE);
while (true)
{
var PollJob = Service.Jobs.Get(JR.ProjectId, JR.JobId).Execute();
Console.WriteLine("Job status" + JR.JobId + ": " + PollJob.Status.State);
if (PollJob.Status.State.Equals("DONE"))
{
Console.WriteLine("JOB Completed");
Console.ReadLine();
return;
}
}
}
catch (Exception e)
{
Console.WriteLine("Error Occurred: " + e.Message);
}
Console.ReadLine();
}
public static JobReference JobUpload(string project, string dataset, string tableId, string filePath, TableSchema schema, string createDisposition, string writeDisposition, char delimiter, BigqueryService BigQueryService)
{
TableReference DestTable = new TableReference();
DestTable.ProjectId = project;
DestTable.DatasetId = dataset;
DestTable.TableId = tableId;
Job Job = new Job();
JobConfiguration Config = new JobConfiguration();
JobConfigurationLoad ConfigLoad = new JobConfigurationLoad();
ConfigLoad.Schema = schema;
ConfigLoad.DestinationTable = DestTable;
ConfigLoad.Encoding = "ISO-8859-1";
ConfigLoad.CreateDisposition = createDisposition;
ConfigLoad.WriteDisposition = writeDisposition;
ConfigLoad.FieldDelimiter = delimiter.ToString();
ConfigLoad.AllowJaggedRows = true;
ConfigLoad.SourceFormat = "CSV";
ConfigLoad.SkipLeadingRows = 1;
ConfigLoad.MaxBadRecords = 100000;
System.Collections.Generic.IList<string> URIs = new System.Collections.Generic.List<string>();
URIs.Add(filePath);
//You can add N number of CSV Files here
ConfigLoad.SourceUris = URIs;
Config.Load = ConfigLoad;
Job.Configuration = Config;
//set job reference (mainly job id)
JobReference JobRef = new JobReference();
Random r = new Random();
var JobNo = r.Next();
JobRef.JobId = "Job" + JobNo.ToString();
JobRef.ProjectId = project;
Job.JobReference = JobRef;
JobsResource.InsertRequest InsertMediaUpload = new JobsResource.InsertRequest(BigQueryService, Job, Job.JobReference.ProjectId);
var JobInfo = InsertMediaUpload.Execute();
return JobRef;
}
}
}
I using openxml to create a powerpoint from an web app.I created a ppt with charts and opened ppt in openxml sdk productivity tool and code which was generated with that i modified the chart data which is coming from database,Code for which i created to modify the chart data as
created a class for the code in the sdk,in that CreatePart() i added these links
ChartPart chartPart1 = slidePart1.AddNewPart<ChartPart>("rId3");
GenerateChartPart1Content(chartPart1);
// This is below code added
#if true // Injects the chart part modification process
var chartModifier1 = new ChartPartModifier();
chartModifier1.UpdateSecondChartPart(chartPart1);
#endif
EmbeddedPackagePart embeddedPackagePart1 = chartPart1.AddNewPart<EmbeddedPackagePart>("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "rId2");
GenerateEmbeddedPackagePart1Content(embeddedPackagePart1);
and created a class for ChartPartModifier()
public void UpdateSecondChartPart(ChartPart chartPart)
{
// Searchs SeriesText and its Values to replace them with your dynamic data
var seriesLabels = chartPart.ChartSpace.Descendants<SeriesText>().ToList();
var seriesValues = chartPart.ChartSpace.Descendants<Values>().ToList();
var categoryAxis = chartPart.ChartSpace.Descendants<CategoryAxisData>().ToList();
for (int i = 0; i < this._lineSecCharts.Count; ++i)
{
var yourLine = this._lineSecCharts[i];
var label = seriesLabels[i].Descendants<NumericValue>().FirstOrDefault();
var values = seriesValues[i].Descendants<NumericValue>().ToList();
var categories = categoryAxis[i].Descendants<NumericValue>().ToList();
// Replaces the label of the series
label.Text = yourLine.Label;
// Replaces the values of the series
for (int valIdx = 0; valIdx < values.Count(); ++valIdx)
{
values[valIdx].Text = yourLine.Plots[valIdx].Value.ToString();
categories[valIdx].Text = yourLine.Plots[valIdx].Category;
}
}
}
Like this is there any way to modify the data in the table,If so can any one provide me the solution is much appreciated.
I found answer after a research i'm able to update the table values from database using openxml
the below code which(if condition) added between table appending the rows and graphicdata appending
table1.Append(tableProperties1);
table1.Append(tableGrid1);
table1.Append(tableRow1);
table1.Append(tableRow2);
table1.Append(tableRow3);
table1.Append(tableRow4);
table1.Append(tableRow5);
table1.Append(tableRow6);
table1.Append(tableRow7);
#if true // Injects the table modification process
TableModifier tableModifier = new TableModifier();//Create a class
tableModifier.UpdateTable(table1);//Send the table object of which you wanted to update
#endif
graphicData1.Append(table1);
graphic1.Append(graphicData1);
In class of TableModifier
using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.Packaging;
public class TableModifier
{
public TableModifier()
{
this.SetupDataSource();
}
public void UpdateTable(Table table)
{
var rows = table.Descendants<TableRow>().ToList();
for (int r = 0; r < rows.Count(); ++r)
{
var yourRow = this._rows[r];
var cells = rows[r].Descendants<TableCell>().ToList();
for (int c = 0; c < cells.Count(); ++c)
{
var yourCell = yourRow.Cells[c];
var text = cells[c].Descendants<Text>().FirstOrDefault();
if (text != null)
{
text.Text = yourCell.Value;
}
}
}
}
private void SetupDataSource()
{
this._rows.Add(new Row()
{
Cells = new List<Cell>()
{
new Cell(){ Value = "Products" },
new Cell(){ Value = "2010" },
new Cell(){ Value = "2011" },
new Cell(){ Value = "2012" },
}
});
for (int i = 0; i < 6; ++i)
{
var productName = string.Format("Product {0}", (char)(i + 'A'));
this._rows.Add(new Row()
{
Cells = new List<Cell>()
{
new Cell(){ Value = productName },
new Cell(){ Value = "10%" },
new Cell(){ Value = "20%" },
new Cell(){ Value = "30%" },
}
});
}
}
#region Private Data Structure
private class Row
{
public List<Cell> Cells { get; set; }
}
private class Cell
{
public string Value { get; set; }
}
#endregion
private List<Row> _rows = new List<Row>();
}
I am reading in an XML file that is shown in the attached image. I'm reading it in using URLRequest, which works properly. The next thing I'd like to do is to populate an arraylist with all of the "project" nodes. I'm converting the XML to an array, but the source is showing the project as being in the [0] node and the arraylist's length is 1.
What's the proper way to do this so I can loop through all the projects in the arraylist?
private var xmlParameters:XML
private var xmlStoryMap:XMLList;
protected function application1_creationCompleteHandler(event:FlexEvent):void
{
var params:Object;
var xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, xmlloader_onComplete_Handler);
xmlLoader.addEventListener(IOErrorEvent.IO_ERROR,IOError_handler);
xmlLoader.load(new URLRequest("myXML.xml"));
}
protected function xmlloader_onComplete_Handler(event:Event):void
{
var loader:URLLoader = URLLoader(event.target)
xmlParameters = new XML(loader.data);
xmlStoryMap = xmlParameters.projects;
initializeMap();
}
protected function initializeMap():void
{
var testlist:ArrayList = new ArrayList();
testlist.source = convertXMLtoArray(xmlStoryMap.project);
}
private function convertXMLtoArray(file:String):Array
{
var xml:XMLDocument = new XMLDocument(file);
var decoder:SimpleXMLDecoder = new SimpleXMLDecoder;
var data:Object = decoder.decodeXML(xml);
var array:Array = ArrayUtil.toArray(data);
return array;
}
If you don't want to have a loop issue, use this instead
protected function xmlloader_onComplete_Handler(event:Event):void
{
var loader:URLLoader = URLLoader(event.target)
var xmlString:String = loader.data;
initializeMap(xmlString);
}
protected function initializeMap(xmlString:String):void
{
var testlist:ArrayList = new ArrayList();
testlist.source = convertXMLtoArray(xmlString);
}
private function convertXMLtoArray(xmlString:String):Array
{
var xmlDoc:XMLDocument = new XMLDocument(xmlString);
var decoder:SimpleXMLDecoder = new SimpleXMLDecoder();
var data:Object = decoder.decodeXML(xmlDoc);
return ArrayUtil.toArray(data.storymap.projects.project);
}
For looping through the projects,
for each(var projectXML:XML in xmlParameters.projects.project)
{
// Do operation
}