I am creating a application to work with office 365 Excel in sharepoint with help of Microsoft Graph REST API V1.0. With following code I am able to create a sub-directory in root directory. How can i add Excel file to my root directory.
var driveItem = new DriveItem
{
Name = name,
Folder = new Folder
{
},
};
await graphClient.Me.Drive.Root.Children.Request().AddAsync(driveItem);
The following code creates an excel workbook and adds it to your root directory. I have tested it and it works fine.
Drive item end point can be used to upload the file.
A similar question was asked here. Please refer it for more details
The following code will create the excel file
public static void CreateWorkbook(Stream stream)
{
// By default, AutoSave = true, Editable = true, and Type = xlsx.
var spreadsheetDocument =
SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook);
// Add a WorkbookPart to the document.
var workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
// Add a WorksheetPart to the WorkbookPart.
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Add Sheets to the Workbook.
var sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
// Append a new worksheet and associate it with the workbook.
var sheet = new Sheet()
{ Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "mySheet" };
sheets.Append(sheet);
workbookpart.Workbook.Save();
// Close the document.
spreadsheetDocument.Close();
}
Use the following to upload the above-created file in C#
using (var stream = new MemoryStream())
{
CreateWorkbook(stream);
stream.Seek(0, SeekOrigin.Begin);
var driveItem = await client.Me
.Drive
.Root
.ItemWithPath("SampleWorkbook1.xlsx")
.Content
.Request()
.PutAsync<DriveItem>(stream);
}
Related
I want to display number 3123.45 as 3,123.45 by using C# as follow coding. I tried many codes but didn't find good example and code.
public static void CreateSpreadsheetWorkbook(string filepath)
{
// Create a spreadsheet document by supplying the filepath.
// By default, AutoSave = true, Editable = true, and Type = xlsx.
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook);
// Add a WorkbookPart to the document.
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Add Sheets to the Workbook.
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
// Append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet() { Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "mySheet" };
sheets.Append(sheet);
workbookpart.Workbook.Save();
// Close the document.
spreadsheetDocument.Close();
}
You need to set the style for the selected column that you want:
sheet.Column(columnIndex).Style.Numberformat.Format = "#,##0.00";
I think you can also do this for cells.
I am trying to export a datatable using closed xml but it gives me blank sheet.
Here is my code
[HttpPost]
public FileResult ExportExcel()
{
List<ProductModel> productDetails = (List<ProductModel>)Session["CartItems"];
System.Data.DataTable dtExcel = CategoryDAL.ToDataTable(productDetails);
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dtExcel);
using (MemoryStream stream = new MemoryStream())
{
wb.SaveAs(stream);
return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Grid.xlsx");
}
}
}
When I debug I can see that datatable has the data but it exports a blank one
Hey I've written an excelexporter for our proposes on my own.
I used this tutorial to get started with excel exporting:
http://www.dispatchertimer.com/tutorial/how-to-create-an-excel-file-in-net-using-openxml-part-2-export-a-collection-to-spreadsheet/
http://www.dispatchertimer.com/tutorial/how-to-create-an-excel-file-in-net-using-openxml-part-3-add-stylesheet-to-the-spreadsheet/ (for styling proposes)
and here is a code snippet how I run an excel export in a controller:
public async Task<FileResult> DownloadExcel(long id, CancellationToken token)
{
var entites= await _someRepository.GetSomethingAsync(id, token).ConfigureAwait(false);
var report = _excelExporter.Export(entites.OrderByDescending(d => d.Date));
return File(report, MimeTypes.GetMimeType("excel.xlsx"), $"entities.xlsx");
}
Generating the excel spreadsheet is done with a memory stream. Here are some lines how I begin creating the excel file:
using (MemoryStream mem = new MemoryStream())
{
using (var document = SpreadsheetDocument.Create(mem, SpreadsheetDocumentType.Workbook))
{
var workbookPart = document.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
var worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
var sheets = workbookPart.Workbook.AppendChild(new Sheets());
var sheet = new Sheet
{
Id = workbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Report"
};
sheets.Append(new[] { sheet });
workbookPart.Workbook.Save();
var sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());
// Constructing header
var row = new Row();
// This needs to get adjusted for your needs
// it returns IEnumerable<Cell>
row.Append(GenerateHeaderCells(/*FillMe*/));
// Insert the header row to the Sheet Data
sheetData.AppendChild(row);
foreach (var entity in data)
{
row = new Row();
//This needs to get adjusted
// it returns IEnumerable<Cell>
row.Append(GenerateCells(/*FillMe*/));
sheetData.AppendChild(row);
}
worksheetPart.Worksheet.Save();
}
return mem.ToArray();
}
I had no MS-Office installed on my system and my requirement was to generate the file and send it to email. So ultimate goal was to send the excel to admin user. When i wrote the code to send it to email and checked email, excel showed the data but when I was returning it from the same code, It was blank sheet. Maybe I should have used interop dlls.
The following method creates a new workbook, and inserts two validator dropdowns:
public static void ForValidator() {
using (SpreadsheetDocument myDoc = SpreadsheetDocument.Create("validator output.xlsx", SpreadsheetDocumentType.Workbook)) {
WorkbookPart workbookpart = myDoc.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
SheetData sheetData_ = new SheetData();
worksheetPart.Worksheet = new Worksheet(sheetData_);
Sheets sheets_ = myDoc.WorkbookPart.Workbook.AppendChild(new Sheets());
sheets_.AppendChild(new Sheet() {
Id = myDoc.WorkbookPart.GetIdOfPart(myDoc.WorkbookPart.WorksheetParts.First()), SheetId = 1, Name = "Sheet1"
});
DataValidations dataValidations = new DataValidations();
DataValidation dataValidation = new DataValidation() {
Type = DataValidationValues.List, AllowBlank = true, SequenceOfReferences = new ListValue<StringValue>() { InnerText = "F2:F3" }
};
Formula1 formula = new Formula1();
formula.Text = "\"Selection 1,Selection 2,Selection 3\"";
dataValidation.Append(formula);
dataValidations.Append(dataValidation);
worksheetPart.Worksheet.AppendChild(dataValidations);
}
}
Can the same routine be modified to instead just open an existing "validator output.xlsx" file and do the same thing?
For over a week I've tried everything I know to try and have come up with nothing. Thank you for any help.
I am trying to create a simple excel file with multiple sheets using open xml, unfortunately the file does not open after it's being created.
After the file is generated, when I open it with Microsoft Excel it says
We found a problem, do you want to recover as much as we can?
using (SpreadsheetDocument spreedDoc = SpreadsheetDocument.Create(filePath,
DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
WorkbookPart wbPart = spreedDoc.WorkbookPart;
wbPart = spreedDoc.AddWorkbookPart();
wbPart.Workbook = new Workbook();
Sheets sheets = wbPart.Workbook.AppendChild(new Sheets());
foreach (var sheetData in excelSheetData)
{
// Add a blank WorksheetPart.
WorksheetPart worksheetPart = wbPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
string relationshipId = wbPart.GetIdOfPart(worksheetPart);
// 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 sheetNameToWrite = sheetName;
if (string.IsNullOrWhiteSpace(sheetNameToWrite))
{
sheetNameToWrite = "Sheet"+sheetId;
}
// Append the new worksheet and associate it with the workbook.
Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
sheets.AppendChild(sheet);
}
//wbPart.Workbook.Sheets.AppendChild(sheet);
wbPart.Workbook.Save();
}
On trying to Repair in excel gives below message
-<repairedRecords summary="Following is a list of repairs:">
<repairedRecord>Repaired Records: Worksheet properties from /xl/workbook.xml part (Workbook)</repairedRecord>
</repairedRecords>
</recoveryLog>
Have you seen this?
http://www.mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm
The necessary steps to create a functional excel file with multiple worksheets in OpenXML (that work for me) are as follows:
using (SpreadsheetDocument spreadsheet = SpreadsheetDocument.Create(path, SpreadsheetDocumentType.Workbook))
{
spreadsheet.AddWorkbookPart();
spreadsheet.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
spreadsheet.WorkbookPart.Workbook.Append(new BookViews(new WorkbookView()));
WorkbookStylesPart workbookStylesPart = spreadsheet.WorkbookPart.AddNewPart<WorkbookStylesPart>("rIdStyles");
Stylesheet stylesheet = new Stylesheet();
workbookStylesPart.Stylesheet = stylesheet;
workbookStylesPart.Stylesheet.Save();
for (int worksheetNo = 1; worksheetNo < worksheetCountYouWantToCreate; worksheetNo++)
{
string workSheetID = "rId" + worksheetNo;
string worksheetName = "worksheet" + worksheetNo;
WorksheetPart newWorksheetPart = spreadsheet.WorkbookPart.AddNewPart<WorksheetPart>();
newWorksheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet();
newWorksheetPart.Worksheet.AppendChild(new DocumentFormat.OpenXml.Spreadsheet.SheetData());
// write data here
// ...
// ...
newWorksheetPart.Worksheet.Save();
if (worksheetNo == 1)
spreadsheet.WorkbookPart.Workbook.AppendChild(new DocumentFormat.OpenXml.Spreadsheet.Sheets());
spreadsheet.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>().AppendChild(new DocumentFormat.OpenXml.Spreadsheet.Sheet()
{
Id = spreadsheet.WorkbookPart.GetIdOfPart(newWorksheetPart),
SheetId = (uint)worksheetNo,
Name = worksheetName
});
}
spreadsheet.WorkbookPart.Workbook.Save();
}
I am building a .net core 2.0 app in OSX, its a WebAPI app that when an API endpoint is hit creates a .xlsx with dummy data. When I try to run it (dotnet run) I get
System.UnauthorizedAccessException: Access to the path '/Users/myuser/projects/myproject' is denied. ---> System.IO.IOException: Permission denied
I have tried running it as sudo and changing the folder it is writing to and neither helped
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
CreatePackage("./");
return "value";
}
public void CreatePackage(string filePath)
{
using (SpreadsheetDocument package = SpreadsheetDocument.Create(filePath, SpreadsheetDocumentType.Workbook))
{
CreateParts(package);
}
}
private void CreateParts(SpreadsheetDocument document)
{
WorkbookPart workbookPart = document.AddWorkbookPart();
GenerateWorkbookPartContent(workbookPart);
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>("rId1");
GenerateWorksheetPartContent(worksheetPart);
}
private void GenerateWorkbookPartContent(WorkbookPart workbookPart)
{
Workbook workbook = new Workbook();
workbook.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
Sheets sheets = new Sheets();
Sheet sheet = new Sheet() { Name = "Sheet", SheetId = (UInt32Value)1U, Id = "rId1" };
sheets.Append(sheet);
workbook.Append(sheets);
workbookPart.Workbook = workbook;
}
private void GenerateWorksheetPartContent(WorksheetPart worksheetPart)
{
Worksheet worksheet = new Worksheet();
SheetData sheetData = new SheetData();
Row row = new Row();
Cell cell = new Cell() { CellReference = "A1", DataType = CellValues.InlineString };
InlineString inlineString = new InlineString();
Text text = new Text();
text.Text = "hello";
inlineString.Append(text);
cell.Append(inlineString);
row.Append(cell);
sheetData.Append(row);
worksheet.Append(sheetData);
worksheetPart.Worksheet = worksheet;
}
This is the main parts of the class, I am creating the file (for now) in the project folder. I saw posts about giving read write permissions to all of my files for the CLI but that doesn't seem ideal. Also I saw this about setting attributes on files, but this is the OpenXml spreadsheet create method and as far as I can tell it doesnt have anything about setting file permissions (and it would need to be at the folder anyway)
Any help would be much appreciated
I figured it out, the filepath I was sending was a folderpath not a filepath, issue resolved
[HttpGet("{id}")]
public string Get(int id)
{
CreatePackage("./testfile.xlsx");
return "value";
}