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.
Related
I have a problem when saving and opening a file with OpenXml library. Here is my code:
public static void SaveExcel(List<Dictionary<string, object>> listData, List<string> entityTypes, string appName)
{
using (var ms = new MemoryStream())
using (var excel = SpreadsheetDocument.Create(ms, SpreadsheetDocumentType.Workbook))
{
var workBookPart = excel.AddWorkbookPart();
workBookPart.Workbook = new Workbook();
var workSheetPart = workBookPart.AddNewPart<WorksheetPart>();
var workSheetData = new SheetData();
workSheetPart.Worksheet = new Worksheet(workSheetData);
var sheets = workBookPart.Workbook.AppendChild(new Sheets());
var index = 1;
foreach (var entityType in entityTypes)
{
var sheet = new Sheet
{
Id = excel.WorkbookPart.GetIdOfPart(workSheetPart),
SheetId = 1U,
Name = entityType
};
sheets.AppendChild(sheet);
}
workBookPart.Workbook.Save(ms);
File.WriteAllBytes("D:/nothing123.xlsx", ms.ToArray());
}
}
I am pretty sure I did the right thing though I have this error when opening the file:
Excel cannot be opened the file 'nothing123.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and the file extension matches the format of the file.
Any idea whats going on with my code?
I don't know if this is relevant to the tag but I made up my mind to use ClosedXml library since it's much easier to use than OpenXml. I can easily create a DataTable and create an Excel file out of the DataTable which is very convenient. Here is my quick sample code:
Sample Data Table
public DataTable getData() {
DataTable dt = new DataTable();
dt.TableName = "SheetName1";
dt.Columns.Add("FirstName");
dt.Columns.Add("LastName");
var row = dt.NewRow();
row["FirstName"] = "Alvin";
row["LastName"] = "Quezon";
dt.Rows.Add(row);
return dt;
}
Sample Code to Excel to Byte Array
public static byte[] GetExcelBytes(DataTable dataTable)
{
using (var ms = new MemoryStream())
using (var workBook = new XLWorkbook())
{
workBook.Worksheets.Add(dataTable);
workBook.SaveAs(ms);
return ms.ToArray();
}
}
I didn't get any issue when opening the file and with superb minimal code usage.
Hopefully this will help anyone would like to use this in the future.
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);
}
I am trying to get the API to start a download of the excel spreadsheet that has been created. Although, i seem to be running into some hassle. I have tried to also send the Byte array of the Spreadsheets memory stream through to the front-end and go from there, but the excel file is corrupt and does not contain any data.
Controller:
[HttpPost]
[Route("CreateExcelDocument")]
public ActionResult CreateExcelDocument([FromBody] List<BarBillList> model)
{
try
{
byte[] tmp;
using (ExcelController ex = new ExcelController())
{
tmp = ex.createExcelSpreadsheet(barBillExport);
}
string fileName = "xxx.xlsx";
return File(tmp, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
}
catch (Exception e)
{
return null;
}
}
ExcelController class with the spreadsheet creation method:
public byte[] createExcelSpreadsheet(List<BarBillList> barBillExport)
{
DateTime today = DateTime.Today;
using (MemoryStream ms = new MemoryStream())
{
using (SpreadsheetDocument document = SpreadsheetDocument.Create(ms, SpreadsheetDocumentType.Workbook))
{
//Creating the initial document
WorkbookPart workbookPart = document.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
workbookPart.Workbook.Save();
//Styling the doucment
WorkbookStylesPart stylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
stylesPart.Stylesheet = GenerateStyleSheet();
stylesPart.Stylesheet.Save();
//Adding width to the columns
DocumentFormat.OpenXml.Spreadsheet.Columns columns = new DocumentFormat.OpenXml.Spreadsheet.Columns();
columns.Append(new DocumentFormat.OpenXml.Spreadsheet.Column() { Min = 1, Max = 6, Width = 20, CustomWidth = true });
worksheetPart.Worksheet.Append(columns);
//Creating the worksheet part to add the data to
Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "BarBill" };
sheets.Append(sheet);
SheetData sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());
//Creating the first Header Row
Row row = new Row();
row.Append(
ConstructCell("Name", CellValues.String, true),
ConstructCell("Last Payment Date", CellValues.String, true),
ConstructCell("Last Payment Amount", CellValues.String, true),
ConstructCell("Current Balance", CellValues.String, true));
sheetData.AppendChild(row);
//Appending the data into their respective columns
foreach (var ent in barBillExport)
{
row = new Row();
row.Append(
ConstructCell(ent.Name.ToString(), CellValues.String, false),
ConstructCell((ent.LastPaymentDate.ToString().Length > 0) ? ent.LastPaymentDate.ToString() : "", CellValues.String, false),
ConstructCell((ent.LastPayment.ToString().Length > 0) ? ent.LastPayment.ToString() : "", CellValues.String, false),
ConstructCell((ent.TotalBalance.ToString().Length > 0) ? ent.TotalBalance.ToString() : "", CellValues.String, false));
sheetData.AppendChild(row);
}
worksheetPart.Worksheet.Save();
}
return ms.ToArray();
}
}
EDIT
Front End Service:
createExcelDocument(model: BillList[]): any {
return this.http.post(this.getBarBillsUrl + "/CreateExcelDocument", model)
.map(this.helper.extractData)
.catch(this.helper.handleError);
}
I am aware that the mapper does not need to be there. But im keeping it there should i need to bring the byte array through to the front and go from there.
Any direction or guidance on the matter would be greatly appreciated.
Thanks.
Solution Found for those interested or facing a similar issue(Please see below answers for author)
I added the { responseType: ResponseContentType.Blob } to the service call in TypeScript.
It then returned me a blob of the spreadsheet. From there, within the typescript i ran it through another method:
private saveAsBlob(data: any) {
const year = this.today.getFullYear();
const month = this.today.getMonth();
const date = this.today.getDate();
const dateString = year + '-' + month + '-' + date;
const file = new File([data], 'BarBill ' + dateString + '.xlsx',
{ type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
FileSaver.saveAs(file);
}
To then get my file to download client side.
Thanks very much to all. Especially the author of the answer.
You need to tell Angular that the response is not JSON format , and so it will not try to parse it. Try changing your code to:
createExcelDocument(model: BillList[]): any {
return this.http.post(this.getBarBillsUrl + "/CreateExcelDocument",
model, { responseType: ResponseContentType.Blob })
.map(this.helper.extractData)
.catch(this.helper.handleError);
}
The above code for binary format, but for excel files you should use this below code:
const httpOptions = {
headers: new HttpHeaders({ 'responseType': 'ResponseContentType.Blob',
'Content-Type': 'application/vnd.ms-excel'})};
createExcelDocument(model: BillList[]): any {
return this.http.post(this.getBarBillsUrl + "/CreateExcelDocument",
model, httpOptions )
.map(this.helper.extractData)
.catch(this.helper.handleError);
}
Your "return ms.ToArray();" line needs to move inside the using and possibly add "document.Close();":
public byte[] createExcelSpreadsheet(List<BarBillList> barBillExport)
{
DateTime today = DateTime.Today;
using (MemoryStream ms = new MemoryStream())
{
using (SpreadsheetDocument document = SpreadsheetDocument.Create(ms, SpreadsheetDocumentType.Workbook))
{
//Creating the initial document
...
//Styling the doucment
...
//Adding width to the columns
...
//Creating the worksheet part to add the data to
...
SheetData sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());
//Creating the first Header Row
...
//Appending the data into their respective columns
foreach (var ent in barBillExport)
{
...
}
worksheetPart.Worksheet.Save();
document.Close();
return ms.ToArray();
}
}
}
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";
}
Please help me to solve the problem, when i save the excel file throw this error i convert the excel file to zip file.
zip.Save(#"" + root + "/" + "" + userid + ".zip");
the process cannot access the file because it is being used by another process
my code is below
using (SpreadsheetDocument document = SpreadsheetDocument.Create(excelFilename, SpreadsheetDocumentType.Workbook))
{
WriteExcelFile(ds, document);
}
private static void WriteExcelFile(DataSet ds, SpreadsheetDocument spreadsheet)
{
spreadsheet.AddWorkbookPart();
spreadsheet.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
spreadsheet.WorkbookPart.Workbook.Append(new BookViews(new WorkbookView()));
// If we don't add a "WorkbookStylesPart", OLEDB will refuse to connect to this .xlsx file !
WorkbookStylesPart workbookStylesPart = spreadsheet.WorkbookPart.AddNewPart<WorkbookStylesPart>("rIdStyles");
Stylesheet stylesheet = new Stylesheet();
workbookStylesPart.Stylesheet = stylesheet;
// Loop through each of the DataTables in our DataSet, and create a new Excel Worksheet for each.
uint worksheetNumber = 1;
foreach (DataTable dt in ds.Tables)
{
// For each worksheet you want to create
string workSheetID = "rId" + worksheetNumber.ToString();
string worksheetName = dt.TableName;
WorksheetPart newWorksheetPart = spreadsheet.WorkbookPart.AddNewPart<WorksheetPart>();
newWorksheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet();
// create sheet data
newWorksheetPart.Worksheet.AppendChild(new DocumentFormat.OpenXml.Spreadsheet.SheetData());
// save worksheet
WriteDataTableToExcelWorksheet(dt, newWorksheetPart);
newWorksheetPart.Worksheet.Save();
// create the worksheet to workbook relation
if (worksheetNumber == 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)worksheetNumber,
Name = dt.TableName
});
worksheetNumber++;
}
spreadsheet.WorkbookPart.Workbook.Save();
}
I see that you have saved your document but you have not closed it. So, it will still be open with the spreadsheetdocument object.
Add the following line after you save the document.
spreadsheet.WorkbookPart.Workbook.Close();
If it doesn't help, kindly provide the full code so that we can look into it further. Good luck.
I think you are not closing all your Workbooks before you try to put them in the Zip-File.
Put this at the end of the Method:
private static void WriteExcelFile(DataSet ds, SpreadsheetDocument spreadsheet)
{
...
spreadsheet.WorkbookPart.Workbook.Close();
}