I am facing a problem while exporting multiple images in Excel Cell.
I am doing it in a simple button click in a page .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using A = DocumentFormat.OpenXml.Drawing;
using Xdr = DocumentFormat.OpenXml.Drawing.Spreadsheet;
using A14 = DocumentFormat.OpenXml.Office2010.Drawing;
using System.IO;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
namespace OpenXMLExport
{
public partial class _Default : System.Web.UI.Page
{
public static string ImageFile = HttpContext.Current.Server.MapPath(#"~\Data\Sunset.jpg");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
DataTable table = GetTable();
DataSet ds = new DataSet();
ds.Tables.Add(table);
ExportDataSet(ds, HttpContext.Current.Server.MapPath(#"~\Data\ImageExport.xlsx"));
}
/// <summary>
/// This example method generates a DataTable.
/// </summary>
static DataTable GetTable()
{
//
// Here we create a DataTable with four columns.
//
DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Image", typeof(string));
//
// Here we add five DataRows.
//
table.Rows.Add(25, "Indocin", "David");
table.Rows.Add(50, "Enebrel", "Sam");
//table.Rows.Add(10, "Hydralazine", "Christoff");
return table;
}
private void ExportDataSet(DataSet ds, string destination)
{
using (var workbook = DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Create(
destination, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
var workbookPart = workbook.AddWorkbookPart();
workbook.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
workbook.WorkbookPart.Workbook.Sheets = new DocumentFormat.OpenXml.Spreadsheet.Sheets();
foreach (System.Data.DataTable table in ds.Tables)
{
var sheetPart = workbook.WorkbookPart.AddNewPart<DocumentFormat.OpenXml.Packaging.WorksheetPart>();
var sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();
sheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData);
//DocumentFormat.OpenXml.Spreadsheet.SheetFormatProperties sheetFormatProperties2 = new DocumentFormat.OpenXml.Spreadsheet.SheetFormatProperties() { DefaultRowHeight = 15D };
//sheetPart.Worksheet.Append(sheetFormatProperties2);
DocumentFormat.OpenXml.Spreadsheet.Sheets sheets =
workbook.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>();
string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);
uint sheetId = 1;
if (sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Count() > 0)
{
sheetId =
sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Select(s => s.SheetId.Value).Max() + 1;
}
DocumentFormat.OpenXml.Spreadsheet.Sheet sheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet()
{ Id = relationshipId, SheetId = sheetId, Name = table.TableName };
sheets.Append(sheet);
DocumentFormat.OpenXml.Spreadsheet.Row headerRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
List<String> columns = new List<string>();
foreach (System.Data.DataColumn column in table.Columns)
{
columns.Add(column.ColumnName);
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName);
headerRow.AppendChild(cell);
}
sheetData.AppendChild(headerRow);
foreach (System.Data.DataRow dsrow in table.Rows)
{
DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
foreach (String col in columns)
{
if (col.ToString() != "Image")
{
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); //
newRow.AppendChild(cell);
}
else
{
DocumentFormat.OpenXml.Packaging.WorksheetPart sheet1 = GetSheetByName(workbookPart, "sheet");
InsertImage(sheet1, 1, 3, 3, 6, new FileStream(ImageFile, FileMode.Open,FileAccess.ReadWrite));
workbook.WorkbookPart.Workbook.Save();
}
}
sheetData.AppendChild(newRow);
}
// Close the document handle.
workbook.Close();
DownloadFile(HttpContext.Current.Server.MapPath(#"~\Data\ImageExport.xlsx"));
//System.Diagnostics.Process.Start(HttpContext.Current.Server.MapPath(#"\ImageExport.xlsx"));
}
}
}
public static void DownloadFile(string filePath)
{
string path = filePath;// HttpContext.Current.Server.MapPath(filePath);
System.IO.FileInfo file = new System.IO.FileInfo(path);
if (file.Exists)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.WriteFile(file.FullName);
HttpContext.Current.Response.End();
}
}
/// <summary>
/// Returns the WorksheetPart for the specified sheet name
/// </summary>
/// <param name="workbookpart">The WorkbookPart</param>
/// <param name="sheetName">The name of the worksheet</param>
/// <returns>Returns the WorksheetPart for the specified sheet name</returns>
private static DocumentFormat.OpenXml.Packaging.WorksheetPart GetSheetByName(DocumentFormat.OpenXml.Packaging.WorkbookPart workbookpart, string sheetName)
{
foreach (DocumentFormat.OpenXml.Packaging.WorksheetPart sheetPart in workbookpart.WorksheetParts)
{
string uri = sheetPart.Uri.ToString();
if (uri.EndsWith(sheetName + ".xml"))
return sheetPart;
}
return null;
}
/// <summary>
/// Inserts the image at the specified location
/// </summary>
/// <param name="sheet1">The WorksheetPart where image to be inserted</param>
/// <param name="startRowIndex">The starting Row Index</param>
/// <param name="startColumnIndex">The starting column index</param>
/// <param name="endRowIndex">The ending row index</param>
/// <param name="endColumnIndex">The ending column index</param>
/// <param name="imageStream">Stream which contains the image data</param>
private static void InsertImage(DocumentFormat.OpenXml.Packaging.WorksheetPart sheet1,
int startRowIndex, int startColumnIndex, int endRowIndex, int endColumnIndex, Stream imageStream)
{
//Inserting a drawing element in worksheet
//Make sure that the relationship id is same for drawing element in worksheet and its relationship part
int drawingPartId = GetNextRelationShipID(sheet1);
DocumentFormat.OpenXml.Spreadsheet.Drawing drawing1 = new DocumentFormat.OpenXml.Spreadsheet.Drawing()
{ Id = "rId" + drawingPartId.ToString() };
//Check whether the WorksheetPart contains VmlDrawingParts (LegacyDrawing element)
if (sheet1.VmlDrawingParts == null)
{
//if there is no VMLDrawing part (LegacyDrawing element) exists, just append the drawing part to the sheet
sheet1.Worksheet.Append(drawing1);
}
else
{
//if VmlDrawingPart (LegacyDrawing element) exists, then find the index of legacy drawing in the sheet and inserts the new drawing element before VMLDrawing part
int legacyDrawingIndex = GetIndexofLegacyDrawing(sheet1);
if (legacyDrawingIndex != -1)
sheet1.Worksheet.InsertAt<DocumentFormat.OpenXml.OpenXmlElement>(drawing1, legacyDrawingIndex);
else
sheet1.Worksheet.Append(drawing1);
}
//Adding the drawings.xml part
DocumentFormat.OpenXml.Packaging.DrawingsPart drawingsPart1
= sheet1.AddNewPart<DocumentFormat.OpenXml.Packaging.DrawingsPart>("rId" + drawingPartId.ToString());
GenerateDrawingsPart1Content(drawingsPart1, startRowIndex, startColumnIndex, endRowIndex, endColumnIndex);
//Adding the image
DocumentFormat.OpenXml.Packaging.ImagePart imagePart1 = drawingsPart1.AddNewPart<DocumentFormat.OpenXml.Packaging.ImagePart>("image/jpeg", "rId1");
imagePart1.FeedData(imageStream);
}
// Generates content of drawingsPart1.
private static void GenerateDrawingsPart1Content(DocumentFormat.OpenXml.Packaging.DrawingsPart drawingsPart1, int startRowIndex, int startColumnIndex, int endRowIndex, int endColumnIndex)
{
Xdr.WorksheetDrawing worksheetDrawing1 = new Xdr.WorksheetDrawing();
worksheetDrawing1.AddNamespaceDeclaration("xdr", "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing");
worksheetDrawing1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main");
Xdr.TwoCellAnchor twoCellAnchor1 = new Xdr.TwoCellAnchor() { EditAs = Xdr.EditAsValues.OneCell };
Xdr.FromMarker fromMarker1 = new Xdr.FromMarker();
Xdr.ColumnId columnId1 = new Xdr.ColumnId();
columnId1.Text = startColumnIndex.ToString();
Xdr.ColumnOffset columnOffset1 = new Xdr.ColumnOffset();
columnOffset1.Text = "38100";
Xdr.RowId rowId1 = new Xdr.RowId();
rowId1.Text = startRowIndex.ToString();
Xdr.RowOffset rowOffset1 = new Xdr.RowOffset();
rowOffset1.Text = "0";
fromMarker1.Append(columnId1);
fromMarker1.Append(columnOffset1);
fromMarker1.Append(rowId1);
fromMarker1.Append(rowOffset1);
Xdr.ToMarker toMarker1 = new Xdr.ToMarker();
Xdr.ColumnId columnId2 = new Xdr.ColumnId();
columnId2.Text = endColumnIndex.ToString();
Xdr.ColumnOffset columnOffset2 = new Xdr.ColumnOffset();
columnOffset2.Text = "542925";
Xdr.RowId rowId2 = new Xdr.RowId();
rowId2.Text = endRowIndex.ToString();
Xdr.RowOffset rowOffset2 = new Xdr.RowOffset();
rowOffset2.Text = "161925";
toMarker1.Append(columnId2);
toMarker1.Append(columnOffset2);
toMarker1.Append(rowId2);
toMarker1.Append(rowOffset2);
Xdr.Picture picture1 = new Xdr.Picture();
Xdr.NonVisualPictureProperties nonVisualPictureProperties1 = new Xdr.NonVisualPictureProperties();
Xdr.NonVisualDrawingProperties nonVisualDrawingProperties1 = new Xdr.NonVisualDrawingProperties() { Id = (DocumentFormat.OpenXml.UInt32Value)2U, Name = "Picture 1" };
//DocumentFormat.OpenXml.Spreadsheet.SheetFormatProperties sheetFormatProperties3
// = new DocumentFormat.OpenXml.Spreadsheet.SheetFormatProperties() { DefaultRowHeight = 15D ,DefaultColumnWidth = 25D};
Xdr.NonVisualPictureDrawingProperties nonVisualPictureDrawingProperties1 = new Xdr.NonVisualPictureDrawingProperties();
A.PictureLocks pictureLocks1 = new A.PictureLocks() { NoChangeAspect = true };
nonVisualPictureDrawingProperties1.Append(pictureLocks1);
nonVisualPictureProperties1.Append(nonVisualDrawingProperties1);
nonVisualPictureProperties1.Append(nonVisualPictureDrawingProperties1);
Xdr.BlipFill blipFill1 = new Xdr.BlipFill();
A.Blip blip1 = new A.Blip() { Embed = "rId1", CompressionState = A.BlipCompressionValues.Print };
blip1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
A.BlipExtensionList blipExtensionList1 = new A.BlipExtensionList();
A.BlipExtension blipExtension1 = new A.BlipExtension() { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" };
A14.UseLocalDpi useLocalDpi1 = new A14.UseLocalDpi() { Val = false };
useLocalDpi1.AddNamespaceDeclaration("a14", "http://schemas.microsoft.com/office/drawing/2010/main");
blipExtension1.Append(useLocalDpi1);
blipExtensionList1.Append(blipExtension1);
blip1.Append(blipExtensionList1);
A.Stretch stretch1 = new A.Stretch();
A.FillRectangle fillRectangle1 = new A.FillRectangle();
stretch1.Append(fillRectangle1);
blipFill1.Append(blip1);
blipFill1.Append(stretch1);
Xdr.ShapeProperties shapeProperties1 = new Xdr.ShapeProperties();
A.Transform2D transform2D1 = new A.Transform2D();
A.Offset offset1 = new A.Offset() { X = 1257300L, Y = 762000L };
A.Extents extents1 = new A.Extents() { Cx = 2943225L, Cy = 2257425L };
transform2D1.Append(offset1);
transform2D1.Append(extents1);
A.PresetGeometry presetGeometry1 = new A.PresetGeometry() { Preset = A.ShapeTypeValues.Rectangle };
A.AdjustValueList adjustValueList1 = new A.AdjustValueList();
presetGeometry1.Append(adjustValueList1);
shapeProperties1.Append(transform2D1);
shapeProperties1.Append(presetGeometry1);
picture1.Append(nonVisualPictureProperties1);
picture1.Append(blipFill1);
picture1.Append(shapeProperties1);
Xdr.ClientData clientData1 = new Xdr.ClientData();
//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)4U };
//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)0U, FillId = (UInt32Value)2U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U, ApplyFill = true };
//CellFormat cellFormat4 = new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)3U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U, ApplyFill = true };
//CellFormat cellFormat5 = new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)4U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U, ApplyFill = true };
//cellFormats1.Append(cellFormat2);
//cellFormats1.Append(cellFormat3);
//cellFormats1.Append(cellFormat4);
//cellFormats1.Append(cellFormat5);
//CellStyles cellStyles1 = new CellStyles() { Count = (UInt32Value)1U };
//CellStyle cellStyle1 = new CellStyle() { Name = "Normal", FormatId = (UInt32Value)0U, BuiltinId = (UInt32Value)0U };
//cellStyles1.Append(cellStyle1);
//twoCellAnchor1.Append(cellStyles1);
//twoCellAnchor1.Append(cellFormats1);
twoCellAnchor1.Append(fromMarker1);
twoCellAnchor1.Append(toMarker1);
twoCellAnchor1.Append(picture1);
twoCellAnchor1.Append(clientData1);
//twoCellAnchor1.Append(sheetFormatProperties3);
worksheetDrawing1.Append(twoCellAnchor1);
drawingsPart1.WorksheetDrawing = worksheetDrawing1;
}
/// <summary>
/// Get the index of legacy drawing element in the specified WorksheetPart
/// </summary>
/// <param name="sheet1">The worksheetPart</param>
/// <returns>Index of legacy drawing</returns>
private static int GetIndexofLegacyDrawing(DocumentFormat.OpenXml.Packaging.WorksheetPart sheet1)
{
for (int i = 0; i < sheet1.Worksheet.ChildElements.Count; i++)
{
DocumentFormat.OpenXml.OpenXmlElement element = sheet1.Worksheet.ChildElements[i];
if (element is DocumentFormat.OpenXml.Spreadsheet.LegacyDrawing)
return i;
}
return -1;
}
/// <summary>
/// Returns the next relationship id for the specified WorksheetPart
/// </summary>
/// <param name="sheet1">The worksheetPart</param>
/// <returns>Returns the next relationship id </returns>
private static int GetNextRelationShipID(DocumentFormat.OpenXml.Packaging.WorksheetPart sheet1)
{
int nextId = 0;
List<int> ids = new List<int>();
foreach (DocumentFormat.OpenXml.Packaging.IdPartPair part in sheet1.Parts)
{
ids.Add(int.Parse(part.RelationshipId.Replace("rId", string.Empty)));
}
if (ids.Count > 0)
nextId = ids.Max() + 1;
else
nextId = 1;
return nextId;
}
}
}
If i try to export a table with one row its working fine .but i am getting problem for multiple rows
DocumentFormat.OpenXml.Packaging.DrawingsPart drawingsPart1
= sheet1.AddNewPart<DocumentFormat.OpenXml.Packaging.DrawingsPart>("rId" + drawingPartId.ToString());
While adding Drawing part of 2nd Row i am getting Error "Only one instance of the type is allowed for this parent."
Kind of Same Error i found
here http://social.msdn.microsoft.com/Forums/office/en-US/8ac6040f-8599-4e20-84fb-4b2390847373/excel-style-part-using-openxml-in-c
But still unable to solve in my case ...I need to use OpenXMl only
In this code, you have been trying to add a new drawing part for every image that you place within worksheet. As per the open xml file format specification for Excel package, there shall be only one drawing part for worksheet and chartsheet. So change your code to append the images (multiple twoCellAnchor tags) within a single drawing part for worksheet. In this way, you can avoid this exception.
Please find the code snippet to import the simple DataTable into Excel workbook using open xml sdf. I hope this will be helpful to achieve your requirement.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ExcelBuilder obj = new ExcelBuilder();
obj.SetDataSource(GetTable());
obj.CreatePackage(#"output.xlsx");
System.Diagnostics.Process.Start("output.xlsx");
}
/// <summary>
/// Get the DataTable instance
/// </summary>
/// <returns>Returns the DataTable instance</returns>
private DataTable GetTable()
{
DataTable table = new DataTable();
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Image", typeof(Image));
table.Rows.Add("AAAA", GetImageFrom64("iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAFqSURBVDhPY/hPAph45sP/xs0XoDwIIMqA2v0v/kfu/PA//tTP/ylLTkBFIQCvARk7X/0P2/3pv8/O7/9ddv4E47jV56CyEIDVgL6jL/4nHP3533f/z/+OQE12G96DbS5fe4I4AyYdfwHW7Lz8wf+OragagpachrIgAKsBzUfe/k9dchzKQwUesw5BWRCA1YDKw+//N607DOWhAqIMqAG6oHz5ASgPFXhOJ8KA8kPv/5cu3gXl/f8/9eTz/26rHvxXmffkv8/kvVBRCMDpgry5m6G8//+1lz7+L9x/7T9f553/rj0Ig0EAqwFh24FeWLAVzC49+uk/b9eV/7xNZ8EGlM3bCRaHARQDbDa+/q+24uV/2RUf/rcs3wMV/f+fr/rIf5G6o/8TJ26BiiAA3ADP9U//S8979F9s4rX/wjOe/W9fdRAqgx/ADbCfexmsUWjCQ7BtxAIULyTP2Pk/eyaqHwkBrIFIPPj/HwAXQanDAoJm4wAAAABJRU5ErkJggg=="));
table.Rows.Add("BBBB", GetImageFrom64("iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAEoSURBVDhPjZM9S8NQFIb9VcUf4NRNRHCxW4sOji4GK8UspRAIghAEBR0yBSczlSKiEiS0XRR0iODg4H+Q17zn3AZDc68+cLlfnOfkHG5W4CBNU7OyYxUkSQLP82R2YRVEUYSbu1zmIAjM6TJWQetojNXBRIbv++Z0Gatg7fILZy9A7/pTSrHhFIxmQCcu6oL3E+BtZDZ/CI5zYOPitfkL7rvAw55bcJBpL8IwNKe/KIMx2fyfoBEK0naD4Glf6qwJWDPHtA/ku2XmLclOKsH380Av8g4w36kLHrf1jllnQxOhqKC4EoFI2JwyEwVsoLUEgwrKIAmeH8qW8AnzX3C9QqKC2/WqpgVZllUSFyr4OFdJcSrbBXEcm5WdqokCO80us2kUcjgBfgCofKZ+pmmmjQAAAABJRU5ErkJggg=="));
table.Rows.Add("CCCC", GetImageFrom64("iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAEUSURBVDhPpZIhc4QwFIQzESdO9gdW9gecrEAgEAgEAoFEIJAIJALJD6hAIBAIBAKBQNw2SydMgNzN3FV8mUne7ibvgSiKAmVZoqoq1HW9wT3PWc/zHFmWIUkSxHGMKIoQBAF838caME0T5nm2wppmHMeVYRhWtgAKl2U58ShkF8DnHQNCeVnRIXp/DGAbgr2ZZk8J79cPK6ydAtI03QV88yZ5tcLaqQVO1mzhpkQ/D2DtFMDPwt70wL6kRKmENljT5i0gDMPdlD+V6Bna3Pc9PM+DYAqfZYZoeK4xb6a56zq4rgvBxRSamKajuW1bOI4DwcUmPEKjaW6a5i+A023ehF5hm/YriEwt/0Hw9+QP8g6uvOAX9G/HbwDThCwAAAAASUVORK5CYII="));
return table;
}
/// <summary>
/// Converts the From64 data into Image instance
/// </summary>
/// <param name="base64String">Image stream in Base64 encoding</param>
/// <returns>Returns the Image instance</returns>
private Image GetImageFrom64(string base64String)
{
MemoryStream stream = new MemoryStream(System.Convert.FromBase64String(base64String));
return Image.FromStream(stream);
}
}
public class ExcelBuilder
{
/// <summary>
/// static field to maintain the track the relationship id
/// </summary>
private static int s_rId;
/// <summary>
/// Field for Data source
/// </summary>
private DataTable m_table;
/// <summary>
/// Collection to maintain string value of cell and to serialize the content in SharedString xml part
/// </summary>
private List<string> sharedStrings = new List<string>();
/// <summary>
/// Collection to maintain the image collection added into the excel workbook
/// </summary>
private Dictionary<string, Image> ImageCollection = new Dictionary<string, Image>();
/// <summary>
/// Set the DataSource of the Excel builder
/// </summary>
/// <param name="table"></param>
public void SetDataSource(DataTable table)
{
m_table = table;
}
/// <summary>
/// Create a new Excel file
/// </summary>
/// <param name="filePath">Path of the output file</param>
public void CreatePackage(string filePath)
{
using (SpreadsheetDocument package = SpreadsheetDocument.Create(filePath, SpreadsheetDocumentType.Workbook))
{
CreateParts(package);
}
}
// Adds child parts and generates content of the specified part.
private void CreateParts(SpreadsheetDocument workbook)
{
WorkbookPart workbookPart1 = workbook.AddWorkbookPart();
GenerateWorkbookPart1Content(workbookPart1);
WorksheetPart worksheetPart1 = workbookPart1.AddNewPart<WorksheetPart>(GetNextRelationShipId());
GenerateWorksheetPart1Content(worksheetPart1);
SharedStringTablePart sharedStringTablePart1 = workbookPart1.AddNewPart<SharedStringTablePart>(GetNextRelationShipId());
GenerateSharedStringTablePart1Content(sharedStringTablePart1);
}
// Generates content of workbookPart1.
private void GenerateWorkbookPart1Content(WorkbookPart workbookPart1)
{
Workbook workbook1 = new Workbook() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "x15" } };
workbook1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
workbook1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
workbook1.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main");
Sheets sheets1 = new Sheets();
Sheet sheet1 = new Sheet() { Name = "Sheet1", SheetId = (UInt32Value)1U, Id = "rId1" };
sheets1.Append(sheet1);
workbook1.Append(sheets1);
workbookPart1.Workbook = workbook1;
}
// Generates content of worksheetPart1.
private void GenerateWorksheetPart1Content(WorksheetPart worksheetPart1)
{
Worksheet worksheet1 = new Worksheet() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "x14ac" } };
worksheet1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
worksheet1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
worksheet1.AddNamespaceDeclaration("x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac");
SheetData sheetData1 = new SheetData();
string drawingrID = GetNextRelationShipId();
AppendSheetData(sheetData1, worksheetPart1, drawingrID);
worksheet1.Append(sheetData1);
if (worksheetPart1.DrawingsPart != null && worksheetPart1.DrawingsPart.WorksheetDrawing != null)
{
Drawing drawing1 = new Drawing() { Id = drawingrID };
worksheet1.Append(drawing1);
}
worksheetPart1.Worksheet = worksheet1;
}
private void AppendSheetData(SheetData sheetData1, WorksheetPart worksheetPart, string drawingrID)
{
for (int rowIndex = 0; rowIndex < m_table.Rows.Count; rowIndex++)
{
Row row = new Row() { RowIndex = (UInt32Value)(rowIndex + 1U) };
DataRow tableRow = m_table.Rows[rowIndex];
for (int colIndex = 0; colIndex < tableRow.ItemArray.Length; colIndex++)
{
Cell cell = new Cell();
CellValue cellValue = new CellValue();
object data = tableRow.ItemArray[colIndex];
if (data is int || data is float || data is double)
{
cellValue.Text = data.ToString();
cell.Append(cellValue);
}
else if (data is string)
{
cell.DataType = CellValues.SharedString;
string text = data.ToString();
if (!sharedStrings.Contains(text))
sharedStrings.Add(text);
cellValue.Text = sharedStrings.IndexOf(text).ToString();
cell.Append(cellValue);
}
else if (data is Image)
{
DrawingsPart drawingsPart = null;
Xdr.WorksheetDrawing worksheetDrawing = null;
if (worksheetPart.DrawingsPart == null)
{
drawingsPart = worksheetPart.AddNewPart<DrawingsPart>(drawingrID);
worksheetDrawing = new Xdr.WorksheetDrawing();
worksheetDrawing.AddNamespaceDeclaration("xdr", "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing");
worksheetDrawing.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main");
drawingsPart.WorksheetDrawing = worksheetDrawing;
}
else if (worksheetPart.DrawingsPart != null && worksheetPart.DrawingsPart.WorksheetDrawing != null)
{
drawingsPart = worksheetPart.DrawingsPart;
worksheetDrawing = worksheetPart.DrawingsPart.WorksheetDrawing;
}
string imagerId = GetNextRelationShipId();
Xdr.TwoCellAnchor cellAnchor = AddTwoCellAnchor(rowIndex, 1, rowIndex, 1, imagerId);
worksheetDrawing.Append(cellAnchor);
ImagePart imagePart = drawingsPart.AddNewPart<ImagePart>("image/png", imagerId);
GenerateImagePartContent(imagePart, data as Image);
}
row.Append(cell);
}
sheetData1.Append(row);
}
}
// Generates content of imagePart1.
private void GenerateImagePartContent(ImagePart imagePart, Image image)
{
MemoryStream memStream = new MemoryStream();
image.Save(memStream, ImageFormat.Png);
memStream.Position = 0;
imagePart.FeedData(memStream);
memStream.Close();
}
private Xdr.TwoCellAnchor AddTwoCellAnchor(int startRow, int startColumn, int endRow, int endColumn, string imagerId)
{
Xdr.TwoCellAnchor twoCellAnchor1 = new Xdr.TwoCellAnchor() { EditAs = Xdr.EditAsValues.OneCell };
Xdr.FromMarker fromMarker1 = new Xdr.FromMarker();
Xdr.ColumnId columnId1 = new Xdr.ColumnId();
columnId1.Text = startColumn.ToString();
Xdr.ColumnOffset columnOffset1 = new Xdr.ColumnOffset();
columnOffset1.Text = "0";
Xdr.RowId rowId1 = new Xdr.RowId();
rowId1.Text = startRow.ToString();
Xdr.RowOffset rowOffset1 = new Xdr.RowOffset();
rowOffset1.Text = "0";
fromMarker1.Append(columnId1);
fromMarker1.Append(columnOffset1);
fromMarker1.Append(rowId1);
fromMarker1.Append(rowOffset1);
Xdr.ToMarker toMarker1 = new Xdr.ToMarker();
Xdr.ColumnId columnId2 = new Xdr.ColumnId();
columnId2.Text = endColumn.ToString();
Xdr.ColumnOffset columnOffset2 = new Xdr.ColumnOffset();
columnOffset2.Text = "152381";
Xdr.RowId rowId2 = new Xdr.RowId();
rowId2.Text = endRow.ToString();
Xdr.RowOffset rowOffset2 = new Xdr.RowOffset();
rowOffset2.Text = "152381";
toMarker1.Append(columnId2);
toMarker1.Append(columnOffset2);
toMarker1.Append(rowId2);
toMarker1.Append(rowOffset2);
Xdr.Picture picture1 = new Xdr.Picture();
Xdr.NonVisualPictureProperties nonVisualPictureProperties1 = new Xdr.NonVisualPictureProperties();
Xdr.NonVisualDrawingProperties nonVisualDrawingProperties1 = new Xdr.NonVisualDrawingProperties() { Id = (UInt32Value)2U, Name = "Picture 1" };
Xdr.NonVisualPictureDrawingProperties nonVisualPictureDrawingProperties1 = new Xdr.NonVisualPictureDrawingProperties();
A.PictureLocks pictureLocks1 = new A.PictureLocks() { NoChangeAspect = true };
nonVisualPictureDrawingProperties1.Append(pictureLocks1);
nonVisualPictureProperties1.Append(nonVisualDrawingProperties1);
nonVisualPictureProperties1.Append(nonVisualPictureDrawingProperties1);
Xdr.BlipFill blipFill1 = new Xdr.BlipFill();
A.Blip blip1 = new A.Blip() { Embed = imagerId };
blip1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
A.BlipExtensionList blipExtensionList1 = new A.BlipExtensionList();
A.BlipExtension blipExtension1 = new A.BlipExtension() { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" };
A14.UseLocalDpi useLocalDpi1 = new A14.UseLocalDpi() { Val = false };
useLocalDpi1.AddNamespaceDeclaration("a14", "http://schemas.microsoft.com/office/drawing/2010/main");
blipExtension1.Append(useLocalDpi1);
blipExtensionList1.Append(blipExtension1);
blip1.Append(blipExtensionList1);
A.Stretch stretch1 = new A.Stretch();
A.FillRectangle fillRectangle1 = new A.FillRectangle();
stretch1.Append(fillRectangle1);
blipFill1.Append(blip1);
blipFill1.Append(stretch1);
Xdr.ShapeProperties shapeProperties1 = new Xdr.ShapeProperties();
A.Transform2D transform2D1 = new A.Transform2D();
A.Offset offset1 = new A.Offset() { X = 0L, Y = 0L };
A.Extents extents1 = new A.Extents() { Cx = 152381L, Cy = 152381L };
transform2D1.Append(offset1);
transform2D1.Append(extents1);
A.PresetGeometry presetGeometry1 = new A.PresetGeometry() { Preset = A.ShapeTypeValues.Rectangle };
A.AdjustValueList adjustValueList1 = new A.AdjustValueList();
presetGeometry1.Append(adjustValueList1);
shapeProperties1.Append(transform2D1);
shapeProperties1.Append(presetGeometry1);
picture1.Append(nonVisualPictureProperties1);
picture1.Append(blipFill1);
picture1.Append(shapeProperties1);
Xdr.ClientData clientData1 = new Xdr.ClientData();
twoCellAnchor1.Append(fromMarker1);
twoCellAnchor1.Append(toMarker1);
twoCellAnchor1.Append(picture1);
twoCellAnchor1.Append(clientData1);
return twoCellAnchor1;
}
/// <summary>
/// Generates the SharedString xml part using the string collection in SharedStrings (List<string>)
/// </summary>
/// <param name="part"></param>
private void GenerateSharedStringTablePart1Content(SharedStringTablePart part)
{
SharedStringTable sharedStringTable1 = new SharedStringTable();
sharedStringTable1.Count = new UInt32Value((uint)sharedStrings.Count);
sharedStringTable1.UniqueCount = new UInt32Value((uint)sharedStrings.Count);
foreach (string item in sharedStrings)
{
SharedStringItem sharedStringItem = new SharedStringItem();
Text text = new Text();
text.Text = item;
sharedStringItem.Append(text);
sharedStringTable1.Append(sharedStringItem);
}
part.SharedStringTable = sharedStringTable1;
}
/// <summary>
/// Gets the next relationship id
/// </summary>
/// <returns></returns>
private string GetNextRelationShipId()
{
s_rId++;
return "rId" + s_rId.ToString();
}
}
Related
I am looking to adjust the template project to add an opening for the door so the door will be flush with the wall system instead of appearing embedded in the skin of the wall any help would be very appreciated.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Xbim.Common;
using Xbim.Common.Step21;
using Xbim.Ifc;
using Xbim.IO;
using Xbim.Ifc4.ActorResource;
using Xbim.Ifc4.DateTimeResource;
using Xbim.Ifc4.ExternalReferenceResource;
using Xbim.Ifc4.PresentationOrganizationResource;
using Xbim.Ifc4.GeometricConstraintResource;
using Xbim.Ifc4.GeometricModelResource;
using Xbim.Ifc4.GeometryResource;
using Xbim.Ifc4.Interfaces;
using Xbim.Ifc4.Kernel;
using Xbim.Ifc4.MaterialResource;
using Xbim.Ifc4.MeasureResource;
using Xbim.Ifc4.ProductExtension;
using Xbim.Ifc4.ProfileResource;
using Xbim.Ifc4.PropertyResource;
using Xbim.Ifc4.QuantityResource;
using Xbim.Ifc4.RepresentationResource;
using Xbim.Ifc4.SharedBldgElements;
namespace HelloWall
{
class Program
{
/// <summary>
/// This sample demonstrates the minimum steps to create a compliant IFC model that contains a single standard case wall
/// </summary>
static int Main()
{
//first create and initialise a model called Hello Wall
Console.WriteLine("Initialising the IFC Project....");
using (var model = CreateandInitModel("HelloWall"))
{
if (model != null)
{
IfcBuilding building = CreateBuilding(model, "Default Building");
IfcWallStandardCase wall = CreateWall(model, 4000, 300, 2400);
if (wall != null) AddPropertiesToWall(model, wall);
using (var txn = model.BeginTransaction("Add Wall"))
{
building.AddElement(wall);
txn.Commit();
}
if (wall != null)
{
try
{
Console.WriteLine("Standard Wall successfully created....");
//write the Ifc File
model.SaveAs("HelloWallIfc4.ifc", IfcStorageType.Ifc);
Console.WriteLine("HelloWallIfc4.ifc has been successfully written");
}
catch (Exception e)
{
Console.WriteLine("Failed to save HelloWall.ifc");
Console.WriteLine(e.Message);
}
}
}
else
{
Console.WriteLine("Failed to initialise the model");
}
}
Console.WriteLine("Press any key to exit to view the IFC file....");
Console.ReadKey();
LaunchNotepad("HelloWallIfc4.ifc");
return 0;
}
private static void LaunchNotepad(string fileName)
{
Process p;
try
{
p = new Process {StartInfo = {FileName = fileName, CreateNoWindow = false}};
p.Start();
}
catch (Exception ex)
{
Console.WriteLine("Exception Occurred :{0},{1}",
ex.Message, ex.StackTrace);
}
}
private static IfcBuilding CreateBuilding(IfcStore model, string name)
{
using (var txn = model.BeginTransaction("Create Building"))
{
var building = model.Instances.New<IfcBuilding>();
building.Name = name;
building.CompositionType = IfcElementCompositionEnum.ELEMENT;
var localPlacement = model.Instances.New<IfcLocalPlacement>();
building.ObjectPlacement = localPlacement;
var placement = model.Instances.New<IfcAxis2Placement3D>();
localPlacement.RelativePlacement = placement;
placement.Location = model.Instances.New<IfcCartesianPoint>(p=>p.SetXYZ(0,0,0));
//get the project there should only be one and it should exist
var project = model.Instances.OfType<IfcProject>().FirstOrDefault();
project?.AddBuilding(building);
txn.Commit();
return building;
}
}
/// <summary>
/// Sets up the basic parameters any model must provide, units, ownership etc
/// </summary>
/// <param name="projectName">Name of the project</param>
/// <returns></returns>
private static IfcStore CreateandInitModel(string projectName)
{
//first we need to set up some credentials for ownership of data in the new model
var credentials = new XbimEditorCredentials
{
ApplicationDevelopersName = "xbim developer",
ApplicationFullName = "Hello Wall Application",
ApplicationIdentifier = "HelloWall.exe",
ApplicationVersion = "1.0",
EditorsFamilyName = "Team",
EditorsGivenName = "xbim",
EditorsOrganisationName = "xbim developer"
};
//now we can create an IfcStore, it is in Ifc4 format and will be held in memory rather than in a database
//database is normally better in performance terms if the model is large >50MB of Ifc or if robust transactions are required
var model = IfcStore.Create(credentials, IfcSchemaVersion.Ifc4,XbimStoreType.InMemoryModel);
//Begin a transaction as all changes to a model are ACID
using (var txn = model.BeginTransaction("Initialise Model"))
{
//create a project
var project = model.Instances.New<IfcProject>();
//set the units to SI (mm and metres)
project.Initialize(ProjectUnits.SIUnitsUK);
project.Name = projectName;
//now commit the changes, else they will be rolled back at the end of the scope of the using statement
txn.Commit();
}
return model;
}
/// <summary>
/// This creates a wall and it's geometry, many geometric representations are possible and extruded rectangular footprint is chosen as this is commonly used for standard case walls
/// </summary>
/// <param name="model"></param>
/// <param name="length">Length of the rectangular footprint</param>
/// <param name="width">Width of the rectangular footprint (width of the wall)</param>
/// <param name="height">Height to extrude the wall, extrusion is vertical</param>
/// <returns></returns>
static private IfcWallStandardCase CreateWall(IfcStore model, double length, double width, double height)
{
//
//begin a transaction
using (var txn = model.BeginTransaction("Create Wall"))
{
var wall = model.Instances.New<IfcWallStandardCase>();
wall.Name = "A Standard rectangular wall";
//represent wall as a rectangular profile
var rectProf = model.Instances.New<IfcRectangleProfileDef>();
rectProf.ProfileType = IfcProfileTypeEnum.AREA;
rectProf.XDim = width;
rectProf.YDim = length;
var insertPoint = model.Instances.New<IfcCartesianPoint>();
insertPoint.SetXY(0, 400); //insert at arbitrary position
rectProf.Position = model.Instances.New<IfcAxis2Placement2D>();
rectProf.Position.Location = insertPoint;
//model as a swept area solid
var body = model.Instances.New<IfcExtrudedAreaSolid>();
body.Depth = height;
body.SweptArea = rectProf;
body.ExtrudedDirection = model.Instances.New<IfcDirection>();
body.ExtrudedDirection.SetXYZ(0, 0, 1);
//parameters to insert the geometry in the model
var origin = model.Instances.New<IfcCartesianPoint>();
origin.SetXYZ(0, 0, 0);
body.Position = model.Instances.New<IfcAxis2Placement3D>();
body.Position.Location = origin;
//Create a Definition shape to hold the geometry
var shape = model.Instances.New<IfcShapeRepresentation>();
var modelContext = model.Instances.OfType<IfcGeometricRepresentationContext>().FirstOrDefault();
shape.ContextOfItems = modelContext;
shape.RepresentationType = "SweptSolid";
shape.RepresentationIdentifier = "Body";
shape.Items.Add(body);
//Create a Product Definition and add the model geometry to the wall
var rep = model.Instances.New<IfcProductDefinitionShape>();
rep.Representations.Add(shape);
wall.Representation = rep;
//now place the wall into the model
var lp = model.Instances.New<IfcLocalPlacement>();
var ax3D = model.Instances.New<IfcAxis2Placement3D>();
ax3D.Location = origin;
ax3D.RefDirection = model.Instances.New<IfcDirection>();
ax3D.RefDirection.SetXYZ(0, 1, 0);
ax3D.Axis = model.Instances.New<IfcDirection>();
ax3D.Axis.SetXYZ(0, 0, 1);
lp.RelativePlacement = ax3D;
wall.ObjectPlacement = lp;
// Where Clause: The IfcWallStandard relies on the provision of an IfcMaterialLayerSetUsage
var ifcMaterialLayerSetUsage = model.Instances.New<IfcMaterialLayerSetUsage>();
var ifcMaterialLayerSet = model.Instances.New<IfcMaterialLayerSet>();
var ifcMaterialLayer = model.Instances.New<IfcMaterialLayer>();
ifcMaterialLayer.LayerThickness = 10;
ifcMaterialLayerSet.MaterialLayers.Add(ifcMaterialLayer);
ifcMaterialLayerSetUsage.ForLayerSet = ifcMaterialLayerSet;
ifcMaterialLayerSetUsage.LayerSetDirection = IfcLayerSetDirectionEnum.AXIS2;
ifcMaterialLayerSetUsage.DirectionSense = IfcDirectionSenseEnum.NEGATIVE;
ifcMaterialLayerSetUsage.OffsetFromReferenceLine = 150;
// Add material to wall
var material = model.Instances.New<IfcMaterial>();
material.Name = "some material";
var ifcRelAssociatesMaterial = model.Instances.New<IfcRelAssociatesMaterial>();
ifcRelAssociatesMaterial.RelatingMaterial = material;
ifcRelAssociatesMaterial.RelatedObjects.Add(wall);
ifcRelAssociatesMaterial.RelatingMaterial = ifcMaterialLayerSetUsage;
// IfcPresentationLayerAssignment is required for CAD presentation in IfcWall or IfcWallStandardCase
var ifcPresentationLayerAssignment = model.Instances.New<IfcPresentationLayerAssignment>();
ifcPresentationLayerAssignment.Name = "some ifcPresentationLayerAssignment";
ifcPresentationLayerAssignment.AssignedItems.Add(shape);
// linear segment as IfcPolyline with two points is required for IfcWall
var ifcPolyline = model.Instances.New<IfcPolyline>();
var startPoint = model.Instances.New<IfcCartesianPoint>();
startPoint.SetXY(0, 0);
var endPoint = model.Instances.New<IfcCartesianPoint>();
endPoint.SetXY(4000, 0);
ifcPolyline.Points.Add(startPoint);
ifcPolyline.Points.Add(endPoint);
var shape2D = model.Instances.New<IfcShapeRepresentation>();
shape2D.ContextOfItems = modelContext;
shape2D.RepresentationIdentifier = "Axis";
shape2D.RepresentationType = "Curve2D";
shape2D.Items.Add(ifcPolyline);
rep.Representations.Add(shape2D);
txn.Commit();
return wall;
}
}
/// <summary>
/// Add some properties to the wall,
/// </summary>
/// <param name="model">XbimModel</param>
/// <param name="wall"></param>
static private void AddPropertiesToWall(IfcStore model, IfcWallStandardCase wall)
{
using (var txn = model.BeginTransaction("Create Wall"))
{
CreateElementQuantity(model, wall);
CreateSimpleProperty(model, wall);
txn.Commit();
}
}
private static void CreateSimpleProperty(IfcStore model, IfcWallStandardCase wall)
{
var ifcPropertySingleValue = model.Instances.New<IfcPropertySingleValue>(psv =>
{
psv.Name = "IfcPropertySingleValue:Time";
psv.Description = "";
psv.NominalValue = new IfcTimeMeasure(150.0);
psv.Unit = model.Instances.New<IfcSIUnit>(siu =>
{
siu.UnitType = IfcUnitEnum.TIMEUNIT;
siu.Name = IfcSIUnitName.SECOND;
});
});
var ifcPropertyEnumeratedValue = model.Instances.New<IfcPropertyEnumeratedValue>(pev =>
{
pev.Name = "IfcPropertyEnumeratedValue:Music";
pev.EnumerationReference = model.Instances.New<IfcPropertyEnumeration>(pe =>
{
pe.Name = "Notes";
pe.EnumerationValues.Add(new IfcLabel("Do"));
pe.EnumerationValues.Add(new IfcLabel("Re"));
pe.EnumerationValues.Add(new IfcLabel("Mi"));
pe.EnumerationValues.Add(new IfcLabel("Fa"));
pe.EnumerationValues.Add(new IfcLabel("So"));
pe.EnumerationValues.Add(new IfcLabel("La"));
pe.EnumerationValues.Add(new IfcLabel("Ti"));
});
pev.EnumerationValues.Add(new IfcLabel("Do"));
pev.EnumerationValues.Add(new IfcLabel("Re"));
pev.EnumerationValues.Add(new IfcLabel("Mi"));
});
var ifcPropertyBoundedValue = model.Instances.New<IfcPropertyBoundedValue>(pbv =>
{
pbv.Name = "IfcPropertyBoundedValue:Mass";
pbv.Description = "";
pbv.UpperBoundValue = new IfcMassMeasure(5000.0);
pbv.LowerBoundValue = new IfcMassMeasure(1000.0);
pbv.Unit = model.Instances.New<IfcSIUnit>(siu =>
{
siu.UnitType = IfcUnitEnum.MASSUNIT;
siu.Name = IfcSIUnitName.GRAM;
siu.Prefix = IfcSIPrefix.KILO;
});
});
var definingValues = new List<IfcReal> { new IfcReal(100.0), new IfcReal(200.0), new IfcReal(400.0), new IfcReal(800.0), new IfcReal(1600.0), new IfcReal(3200.0), };
var definedValues = new List<IfcReal> { new IfcReal(20.0), new IfcReal(42.0), new IfcReal(46.0), new IfcReal(56.0), new IfcReal(60.0), new IfcReal(65.0), };
var ifcPropertyTableValue = model.Instances.New<IfcPropertyTableValue>(ptv =>
{
ptv.Name = "IfcPropertyTableValue:Sound";
foreach (var item in definingValues)
{
ptv.DefiningValues.Add(item);
}
foreach (var item in definedValues)
{
ptv.DefinedValues.Add(item);
}
ptv.DefinedUnit = model.Instances.New<IfcContextDependentUnit>(cd =>
{
cd.Dimensions = model.Instances.New<IfcDimensionalExponents>(de =>
{
de.LengthExponent = 0;
de.MassExponent = 0;
de.TimeExponent = 0;
de.ElectricCurrentExponent = 0;
de.ThermodynamicTemperatureExponent = 0;
de.AmountOfSubstanceExponent = 0;
de.LuminousIntensityExponent = 0;
});
cd.UnitType = IfcUnitEnum.FREQUENCYUNIT;
cd.Name = "dB";
});
});
var listValues = new List<IfcLabel> { new IfcLabel("Red"), new IfcLabel("Green"), new IfcLabel("Blue"), new IfcLabel("Pink"), new IfcLabel("White"), new IfcLabel("Black"), };
var ifcPropertyListValue = model.Instances.New<IfcPropertyListValue>(plv =>
{
plv.Name = "IfcPropertyListValue:Colours";
foreach (var item in listValues)
{
plv.ListValues.Add(item);
}
});
var ifcMaterial = model.Instances.New<IfcMaterial>(m =>
{
m.Name = "Brick";
});
var ifcPrValueMaterial = model.Instances.New<IfcPropertyReferenceValue>(prv =>
{
prv.Name = "IfcPropertyReferenceValue:Material";
prv.PropertyReference = ifcMaterial;
});
var ifcMaterialList = model.Instances.New<IfcMaterialList>(ml =>
{
ml.Materials.Add(ifcMaterial);
ml.Materials.Add(model.Instances.New<IfcMaterial>(m =>{m.Name = "Cavity";}));
ml.Materials.Add(model.Instances.New<IfcMaterial>(m => { m.Name = "Block"; }));
});
var ifcMaterialLayer = model.Instances.New<IfcMaterialLayer>(ml =>
{
ml.Material = ifcMaterial;
ml.LayerThickness = 100.0;
});
var ifcPrValueMatLayer = model.Instances.New<IfcPropertyReferenceValue>(prv =>
{
prv.Name = "IfcPropertyReferenceValue:MaterialLayer";
prv.PropertyReference = ifcMaterialLayer;
});
var ifcDocumentReference = model.Instances.New<IfcDocumentReference>(dr =>
{
dr.Name = "Document";
dr.Location = "c://Documents//TheDoc.Txt";
});
var ifcPrValueRef = model.Instances.New<IfcPropertyReferenceValue>(prv =>
{
prv.Name = "IfcPropertyReferenceValue:Document";
prv.PropertyReference = ifcDocumentReference;
});
var ifcTimeSeries = model.Instances.New<IfcRegularTimeSeries>(ts =>
{
ts.Name = "Regular Time Series";
ts.Description = "Time series of events";
ts.StartTime = new IfcDateTime("2015-02-14T12:01:01");
ts.EndTime = new IfcDateTime("2015-05-15T12:01:01");
ts.TimeSeriesDataType = IfcTimeSeriesDataTypeEnum.CONTINUOUS;
ts.DataOrigin = IfcDataOriginEnum.MEASURED;
ts.TimeStep = 604800; //7 days in secs
});
var ifcPrValueTimeSeries = model.Instances.New<IfcPropertyReferenceValue>(prv =>
{
prv.Name = "IfcPropertyReferenceValue:TimeSeries";
prv.PropertyReference = ifcTimeSeries;
});
var ifcAddress = model.Instances.New<IfcPostalAddress>(a =>
{
a.InternalLocation = "Room 101";
a.AddressLines.AddRange(new[] { new IfcLabel("12 New road"), new IfcLabel("DoxField" ) });
a.Town = "Sunderland";
a.PostalCode = "DL01 6SX";
});
var ifcPrValueAddress = model.Instances.New<IfcPropertyReferenceValue>(prv =>
{
prv.Name = "IfcPropertyReferenceValue:Address";
prv.PropertyReference = ifcAddress;
});
var ifcTelecomAddress = model.Instances.New<IfcTelecomAddress>(a =>
{
a.TelephoneNumbers.Add(new IfcLabel("01325 6589965"));
a.ElectronicMailAddresses.Add(new IfcLabel("bob#bobsworks.com"));
});
var ifcPrValueTelecom = model.Instances.New<IfcPropertyReferenceValue>(prv =>
{
prv.Name = "IfcPropertyReferenceValue:Telecom";
prv.PropertyReference = ifcTelecomAddress;
});
//lets create the IfcElementQuantity
var ifcPropertySet = model.Instances.New<IfcPropertySet>(ps =>
{
ps.Name = "Test:IfcPropertySet";
ps.Description = "Property Set";
ps.HasProperties.Add(ifcPropertySingleValue);
ps.HasProperties.Add(ifcPropertyEnumeratedValue);
ps.HasProperties.Add(ifcPropertyBoundedValue);
ps.HasProperties.Add(ifcPropertyTableValue);
ps.HasProperties.Add(ifcPropertyListValue);
ps.HasProperties.Add(ifcPrValueMaterial);
ps.HasProperties.Add(ifcPrValueMatLayer);
ps.HasProperties.Add(ifcPrValueRef);
ps.HasProperties.Add(ifcPrValueTimeSeries);
ps.HasProperties.Add(ifcPrValueAddress);
ps.HasProperties.Add(ifcPrValueTelecom);
});
//need to create the relationship
model.Instances.New<IfcRelDefinesByProperties>(rdbp =>
{
rdbp.Name = "Property Association";
rdbp.Description = "IfcPropertySet associated to wall";
rdbp.RelatedObjects.Add(wall);
rdbp.RelatingPropertyDefinition = ifcPropertySet;
});
}
private static void CreateElementQuantity(IfcStore model, IfcWallStandardCase wall)
{
//Create a IfcElementQuantity
//first we need a IfcPhysicalSimpleQuantity,first will use IfcQuantityLength
var ifcQuantityArea = model.Instances.New<IfcQuantityLength>(qa =>
{
qa.Name = "IfcQuantityArea:Area";
qa.Description = "";
qa.Unit = model.Instances.New<IfcSIUnit>(siu =>
{
siu.UnitType = IfcUnitEnum.LENGTHUNIT;
siu.Prefix = IfcSIPrefix.MILLI;
siu.Name = IfcSIUnitName.METRE;
});
qa.LengthValue = 100.0;
});
//next quantity IfcQuantityCount using IfcContextDependentUnit
var ifcContextDependentUnit = model.Instances.New<IfcContextDependentUnit>(cd =>
{
cd.Dimensions = model.Instances.New<IfcDimensionalExponents>(de =>
{
de.LengthExponent = 1;
de.MassExponent = 0;
de.TimeExponent = 0;
de.ElectricCurrentExponent = 0;
de.ThermodynamicTemperatureExponent = 0;
de.AmountOfSubstanceExponent = 0;
de.LuminousIntensityExponent = 0;
});
cd.UnitType = IfcUnitEnum.LENGTHUNIT;
cd.Name = "Elephants";
});
var ifcQuantityCount = model.Instances.New<IfcQuantityCount>(qc =>
{
qc.Name = "IfcQuantityCount:Elephant";
qc.CountValue = 12;
qc.Unit = ifcContextDependentUnit;
});
//next quantity IfcQuantityLength using IfcConversionBasedUnit
var ifcConversionBasedUnit = model.Instances.New<IfcConversionBasedUnit>(cbu =>
{
cbu.ConversionFactor = model.Instances.New<IfcMeasureWithUnit>(mu =>
{
mu.ValueComponent = new IfcRatioMeasure(25.4);
mu.UnitComponent = model.Instances.New<IfcSIUnit>(siu =>
{
siu.UnitType = IfcUnitEnum.LENGTHUNIT;
siu.Prefix = IfcSIPrefix.MILLI;
siu.Name = IfcSIUnitName.METRE;
});
});
cbu.Dimensions = model.Instances.New<IfcDimensionalExponents>(de =>
{
de.LengthExponent = 1;
de.MassExponent = 0;
de.TimeExponent = 0;
de.ElectricCurrentExponent = 0;
de.ThermodynamicTemperatureExponent = 0;
de.AmountOfSubstanceExponent = 0;
de.LuminousIntensityExponent = 0;
});
cbu.UnitType = IfcUnitEnum.LENGTHUNIT;
cbu.Name = "Inch";
});
var ifcQuantityLength = model.Instances.New<IfcQuantityLength>(qa =>
{
qa.Name = "IfcQuantityLength:Length";
qa.Description = "";
qa.Unit = ifcConversionBasedUnit;
qa.LengthValue = 24.0;
});
//lets create the IfcElementQuantity
var ifcElementQuantity = model.Instances.New<IfcElementQuantity>(eq =>
{
eq.Name = "Test:IfcElementQuantity";
eq.Description = "Measurement quantity";
eq.Quantities.Add(ifcQuantityArea);
eq.Quantities.Add(ifcQuantityCount);
eq.Quantities.Add(ifcQuantityLength);
});
//need to create the relationship
model.Instances.New<IfcRelDefinesByProperties>(rdbp =>
{
rdbp.Name = "Area Association";
rdbp.Description = "IfcElementQuantity associated to wall";
rdbp.RelatedObjects.Add(wall);
rdbp.RelatingPropertyDefinition = ifcElementQuantity;
});
}
}
}
I will also have questions about assigning materials in the future but for now, I really need help with the opening.
SheetData sheetData = new SheetData();
Row headers = new Row();
headers.Append(new Cell
{
CellValue = new CellValue("Losses"), DataType = CellValues.String, StyleIndex = 2U,
CellReference = new StringValue("A1")
});
headers.Append(new Cell
{
CellValue = new CellValue("Target"), DataType = CellValues.String, StyleIndex = 2U,
CellReference = new StringValue("F1"),
});
sheetData.Append(headers);
// creating headers in one row
sheetData.Append(CreateHeaderRowForExcel(type));
byte level = 1;
foreach (MaterialLossDto obj in data)
{
sheetData.Append(AddRowsRecursion(obj, ref level, sheetData));
}
//create a MergeCells class to hold each MergeCell
MergeCells mergeCells = new MergeCells();
//append a MergeCell to the mergeCells for each set of merged cells
mergeCells.Append(new MergeCell() {Reference = new StringValue("A1:D1")});
mergeCells.Append(new MergeCell() {Reference = new StringValue("F1:G1")});
sheetData.Append(mergeCells);
i create workSheet and step by step fill data in row. when i create headers, i want create one long header with merged cells. but it doesn't work for me. all rows are filled and my long header contains only one cell.
solution is not so obvious. creating merged cells need after all manipulations with WorkSheet. here is all my code
public class ReportLoaderBase<T> : IReportLoader<T> where T : class, IReportDto
{
private const string WorksheetPartId = "partId1";
private protected List<KeyValuePair<string, string>> cellsPair;
public string Download(ReportTypeGeneric<T> genericModel, string fileName)
{
string outputFilePath = $"{FileServiceHelper.OutputDirectory}\\{fileName}";
if (!Directory.Exists(FileServiceHelper.OutputDirectory))
Directory.CreateDirectory(FileServiceHelper.OutputDirectory);
CreateExcelFile(genericModel, outputFilePath);
return outputFilePath;
}
private void CreateExcelFile(ReportTypeGeneric<T> model, string outputFilePath)
{
using SpreadsheetDocument excelFile =
SpreadsheetDocument.Create(outputFilePath, SpreadsheetDocumentType.Workbook);
CreatePartsForExcel(excelFile, model);
}
private protected virtual void CreatePartsForExcel(SpreadsheetDocument excelFile,
ReportTypeGeneric<T> model)
{
SheetData sheetData = GenerateSheetDataForDetails(model.Elements, model.ElementsType);
ContinueCreatingPartsForExcel(excelFile, sheetData);
}
private protected void ContinueCreatingPartsForExcel(SpreadsheetDocument excelFile, SheetData sheetData)
{
WorkbookPart workbookPart = excelFile.AddWorkbookPart();
GenerateWorkbookPartContent(workbookPart);
WorkbookStylesPart workbookStylesPart = workbookPart.AddNewPart<WorkbookStylesPart>("rId3");
GenerateWorkbookStylesPartContentNew(workbookStylesPart);
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>(WorksheetPartId);
GenerateWorksheetPartContent(worksheetPart, sheetData);
}
private protected virtual SheetData GenerateSheetDataForDetails(List<T> data, Type type)
{
SheetData sheetData = new SheetData();
// creating headers in one row
sheetData.Append(CreateHeaderRowForExcel(type));
foreach (var obj in data)
{
// generate values
Row rows = GenerateRowForChildPartDetail(obj);
sheetData.Append(rows);
}
return sheetData;
}
private protected virtual Row CreateHeaderRowForExcel(Type type)
{
Row row = new Row();
foreach (PropertyInfo propertyInfo in type.GetProperties())
{
if (propertyInfo.PropertyType.IsListType())
continue;
// 2U for header
Cell cell = CreateCell(propertyInfo.Name.Replace('_', ' '), 2U);
row.Append(cell);
}
return row;
}
private Cell CreateCell(string text)
{
Cell cell = new Cell();
cell.StyleIndex = 1U;
cell.DataType = ResolveCellDataTypeOnValue(text);
cell.CellValue = new CellValue(text);
return cell;
}
private protected Cell CreateCell(string text, uint styleIndex)
{
Cell cell = new Cell();
cell.StyleIndex = styleIndex;
cell.DataType = ResolveCellDataTypeOnValue(text);
cell.CellValue = new CellValue(text);
return cell;
}
private EnumValue<CellValues> ResolveCellDataTypeOnValue(string text)
{
int intVal;
double doubleVal;
if (int.TryParse(text, out intVal) || double.TryParse(text, out doubleVal))
{
return CellValues.Number;
}
return CellValues.String;
}
private protected virtual Row GenerateRowForChildPartDetail(object model)
{
Row row = new Row();
Type type = model.GetType();
foreach (PropertyInfo propertyInfo in type.GetProperties())
{
if (propertyInfo.PropertyType.IsListType())
continue;
var value = propertyInfo.GetValue(model);
// 1U for text
row.Append(CreateCell(value?.ToString() ?? "", 1U));
}
return row;
}
private void GenerateWorkbookPartContent(WorkbookPart workbookPart)
{
Workbook workbook = new Workbook();
Sheets sheets = new Sheets();
Sheet sheet = new Sheet {Name = "Sheet1", SheetId = 1, Id = WorksheetPartId};
sheets.Append(sheet);
workbook.Append(sheets);
workbookPart.Workbook = workbook;
}
private void GenerateWorksheetPartContent(WorksheetPart worksheetPart, SheetData sheetData)
{
Worksheet worksheet = new Worksheet
{
MCAttributes = new MarkupCompatibilityAttributes
{
Ignorable = "x14ac"
}
};
// configurations
worksheet.AddNamespaceDeclaration("r",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships");
worksheet.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
worksheet.AddNamespaceDeclaration("x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac");
SheetDimension sheetDimension = new SheetDimension {Reference = "A1"};
SheetViews sheetViews = new SheetViews();
SheetView sheetView = new SheetView {TabSelected = true, WorkbookViewId = 0U};
Selection selection = new Selection
{
ActiveCell = "A1",
SequenceOfReferences = new ListValue<StringValue>
{
InnerText = "A1"
}
};
sheetView.Append(selection);
sheetViews.Append(sheetView);
SheetFormatProperties sheetFormatProperties = new SheetFormatProperties
{
DefaultRowHeight = 15D,
DyDescent = 0.25D
};
PageMargins pageMargins = new PageMargins
{
Left = 0.7D,
Right = 0.7D,
Top = 0.75D,
Bottom = 0.75D,
Header = 0.3D,
Footer = 0.3D
};
worksheet.Append(sheetDimension);
worksheet.Append(sheetViews);
worksheet.Append(sheetFormatProperties);
worksheet.Append(sheetData);
worksheet.Append(pageMargins);
worksheetPart.Worksheet = worksheet;
MergeCells(worksheetPart);
}
private void MergeCells(WorksheetPart worksheetPart)
{
if (cellsPair == null)
return;
//create a MergeCells class to hold each MergeCell
MergeCells mergeCells = new MergeCells();
//append a MergeCell to the mergeCells for each set of merged cells
foreach (KeyValuePair<string, string> pair in cellsPair)
{
mergeCells.Append(new MergeCell() {Reference = new StringValue($"{pair.Key}:{pair.Value}")});
}
worksheetPart.Worksheet.InsertAfter(mergeCells, worksheetPart.Worksheet.Elements<SheetData>().First());
}
private void GenerateWorkbookStylesPartContentNew(WorkbookStylesPart workbookStylesPart)
{
Stylesheet stylesheet = new Stylesheet(new Fonts(
new Font(new FontSize() {Val = 14}, new Color() {Rgb = new HexBinaryValue() {Value = "000000"}},
new FontName() {Val = "Times New Roman"}),
new Font(new FontSize() {Val = 14}, new Color() {Rgb = new HexBinaryValue() {Value = "000000"}},
new FontName() {Val = "Times New Roman"}), new Font(new Bold(), new FontSize() {Val = 11},
new Color() {Rgb = new HexBinaryValue() {Value = "000000"}},
new FontName() {Val = "Times New Roman"})
),
new Fills(
new Fill(
new PatternFill()
{
PatternType = PatternValues.None
}),
new Fill(
new PatternFill()
{
PatternType = PatternValues.None
}),
new Fill(
new PatternFill(new ForegroundColor()
{
// change color
Rgb = new HexBinaryValue() {Value = "FFFFAAAA"}
})
{
PatternType = PatternValues.Solid
})
),
new Borders(
new Border(new LeftBorder(), new RightBorder(), new TopBorder(), new BottomBorder(),
new DiagonalBorder()),
new Border(new LeftBorder(new Color() {Auto = true}) {Style = BorderStyleValues.Medium},
new RightBorder(new Color() {Indexed = (UInt32Value) 64U}) {Style = BorderStyleValues.Medium},
new TopBorder(new Color() {Auto = true}) {Style = BorderStyleValues.Medium},
new BottomBorder(new Color() {Indexed = (UInt32Value) 64U}) {Style = BorderStyleValues.Medium},
new DiagonalBorder())
),
new CellFormats(new CellFormat() {FontId = 0, FillId = 0, BorderId = 0, ApplyFont = true},
new CellFormat(new Alignment()
{
Horizontal = HorizontalAlignmentValues.Center, Vertical = VerticalAlignmentValues.Center,
WrapText = true
}) {FontId = 1, FillId = 0, BorderId = 1, ApplyFont = true},
new CellFormat(new Alignment()
{
Horizontal = HorizontalAlignmentValues.Center, Vertical = VerticalAlignmentValues.Center,
WrapText = true
}) {FontId = 2, FillId = 2, BorderId = 1, ApplyFont = true})
);
workbookStylesPart.Stylesheet = stylesheet;
}
}
}
I want to create pie chart on Excel using OpenXml. Is there any source from where i can get help?.
I have already developed the Bar Chart.
Here's my reference:
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using C = DocumentFormat.OpenXml.Drawing.Charts;
using DocumentFormat.OpenXml.Drawing.Charts;
using DocumentFormat.OpenXml.Drawing.Spreadsheet;
using DocumentFormat.OpenXml.Drawing;
I'm using here MemoryStream to create excel file:
WorkbookPart workbookPart = null;
using (var memoryStream = new MemoryStream())
{
using (var excel = SpreadsheetDocument.Create(memoryStream, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook, true))
{
workbookPart = excel.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>("rId1");
Worksheet worksheet = new Worksheet();
SheetData sheetData = new SheetData();
worksheet.Append(sheetData);
worksheetPart.Worksheet = worksheet;
string relationshipId = "rId1";// workbookPart.GetIdOfPart(worksheetPart);
Sheets sheets = new Sheets();
uint sheetId = 1;
string sheetName = "Sheet" + sheetId;
Sheet sheet1 = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
sheets.Append(sheet1);
workbookPart.Workbook.Append(sheets);
//// Add a new drawing to the worksheet.
DrawingsPart drawingsPart = worksheetPart.AddNewPart<DrawingsPart>();
worksheetPart.Worksheet.Append(new DocumentFormat.OpenXml.Spreadsheet.Drawing()
{
Id = worksheetPart.GetIdOfPart(drawingsPart)
});
worksheetPart.Worksheet.Save();
string chartTitle = "Generator Utilisation";
Dictionary<string, int> data = new Dictionary<string, int>();
data.Add("Running", 92);
data.Add("Stopped", 8);
InsertPieChartInSpreadSheet(drawingsPart, chartTitle, data, 1, 1, 17, 8);
excel.Close();
}
FileStream fileStream = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "Plant Summary Report.xlsx", FileMode.Create, FileAccess.Write);
memoryStream.WriteTo(fileStream);
fileStream.Close();
memoryStream.Close();
}
Here is InsertPieChartInSpreadSheet method:
private static void InsertPieChartInSpreadSheet(DrawingsPart drawingsPart,string chartTitle, Dictionary<string, int> data, int startRowIndex, int startColumnIndex, int endRowIndex, int endColumnIndex)
{
ChartPart chartPart = drawingsPart.AddNewPart<ChartPart>();
ChartSpace chartSpace = new ChartSpace();
chartSpace.Append(new EditingLanguage() { Val = new StringValue("en-US") });
DocumentFormat.OpenXml.Drawing.Charts.Chart chart = chartSpace.AppendChild<DocumentFormat.OpenXml.Drawing.Charts.Chart>(
new DocumentFormat.OpenXml.Drawing.Charts.Chart());
PlotArea plotArea = chart.AppendChild<PlotArea>(new PlotArea());
Layout layout = plotArea.AppendChild<Layout>(new Layout());
ManualLayout manualLayout1 = new ManualLayout();
LayoutTarget layoutTarget1 = new LayoutTarget() { Val = LayoutTargetValues.Inner };
LeftMode leftMode1 = new LeftMode() { Val = LayoutModeValues.Edge };
TopMode topMode1 = new TopMode() { Val = LayoutModeValues.Edge };
Left left1 = new Left() { Val = 0.5D };
Top top1 = new Top() { Val = 0.2D };
Width width1 = new Width() { Val = 0.95622038461448768D };
Height height1 = new Height() { Val = 0.54928769841269842D };
manualLayout1.Append(layoutTarget1);
manualLayout1.Append(leftMode1);
manualLayout1.Append(topMode1);
manualLayout1.Append(left1);
manualLayout1.Append(top1);
manualLayout1.Append(width1);
manualLayout1.Append(height1);
layout.Append(manualLayout1);
NoFill noFill = new NoFill();
C.ShapeProperties shapeProperties = new C.ShapeProperties();
DocumentFormat.OpenXml.Drawing.Outline outline15 = new DocumentFormat.OpenXml.Drawing.Outline();
DocumentFormat.OpenXml.Drawing.SolidFill noFill17 = new DocumentFormat.OpenXml.Drawing.SolidFill();
RgbColorModelHex schemeColor29 = new RgbColorModelHex() { Val = "FFFFFF" };
noFill17.Append(schemeColor29);
outline15.Append(noFill17);
shapeProperties.Append(noFill);
shapeProperties.Append(outline15);
plotArea.Append(shapeProperties);
PieChart pieChart = plotArea.AppendChild<PieChart>(new PieChart());
PieChartSeries pieChartSeries = pieChart.AppendChild<PieChartSeries>(new PieChartSeries(
new Index() { Val = (UInt32Value)0U },
new Order() { Val = (UInt32Value)0U },
new SeriesText(new NumericValue() { Text = "PieChartSeries" })));
CategoryAxisData catAx = new CategoryAxisData();
StringReference stringReference = new StringReference();
StringCache stringCache = new StringCache();
PointCount pointCount = new PointCount() { Val = (uint)data.Count };
stringCache.Append(pointCount);
uint i = 0;
foreach (var key in data.Keys)
{
stringCache.AppendChild<StringPoint>(new StringPoint() { Index = new UInt32Value(i) }).Append(new NumericValue(key));
i++;
}
stringReference.Append(stringCache);
catAx.Append(stringReference);
pieChartSeries.Append(catAx);
C.Values values = new C.Values();
NumberReference numberReference = new NumberReference();
NumberingCache numberingCache = new NumberingCache();
i = 0;
foreach (var key in data.Keys)
{
numberingCache.AppendChild<NumericPoint>(new NumericPoint() { Index = new UInt32Value(i) }).Append(new NumericValue(data[key].ToString()));
i++;
}
numberReference.Append(numberingCache);
values.Append(numberReference);
pieChartSeries.Append(values);
AddChartTitle(chart, chartTitle);
pieChart.Append(new AxisId() { Val = new UInt32Value(48650112u) });
pieChart.Append(new AxisId() { Val = new UInt32Value(48672768u) });
CategoryAxis catAx1 = plotArea.AppendChild<CategoryAxis>(new CategoryAxis(new AxisId()
{ Val = new UInt32Value(48650112u) }, new Scaling(new Orientation()
{
Val = new EnumValue<DocumentFormat.OpenXml.Drawing.Charts.OrientationValues>(DocumentFormat.OpenXml.Drawing.Charts.OrientationValues.MinMax)
}),
new AxisPosition() { Val = new EnumValue<AxisPositionValues>(AxisPositionValues.Bottom) },
new TickLabelPosition() { Val = new EnumValue<TickLabelPositionValues>(TickLabelPositionValues.NextTo) },
new CrossingAxis() { Val = new UInt32Value(48672768U) },
new Crosses() { Val = new EnumValue<CrossesValues>(CrossesValues.AutoZero) },
new AutoLabeled() { Val = new BooleanValue(true) },
new LabelAlignment() { Val = new EnumValue<LabelAlignmentValues>(LabelAlignmentValues.Center) },
new LabelOffset() { Val = new UInt16Value((ushort)100) }));
// Add the Value Axis.
ValueAxis valAx = plotArea.AppendChild<ValueAxis>(new ValueAxis(new AxisId() { Val = new UInt32Value(48672768u) },
new Scaling(new Orientation()
{
Val = new EnumValue<DocumentFormat.OpenXml.Drawing.Charts.OrientationValues>(
DocumentFormat.OpenXml.Drawing.Charts.OrientationValues.MinMax)
}),
new AxisPosition() { Val = new EnumValue<AxisPositionValues>(AxisPositionValues.Left) },
new MajorGridlines(),
new DocumentFormat.OpenXml.Drawing.Charts.NumberingFormat()
{
FormatCode = new StringValue("General"),
SourceLinked = new BooleanValue(true)
}, new TickLabelPosition()
{
Val = new EnumValue<TickLabelPositionValues>
(TickLabelPositionValues.NextTo)
}, new CrossingAxis() { Val = new UInt32Value(48650112U) },
new Crosses() { Val = new EnumValue<CrossesValues>(CrossesValues.AutoZero) },
new CrossBetween() { Val = new EnumValue<CrossBetweenValues>(CrossBetweenValues.Between) }));
// Add the chart Legend.
Legend legend = chart.AppendChild<Legend>(new Legend(new LegendPosition() { Val = new EnumValue<LegendPositionValues>(LegendPositionValues.Bottom) },
new Layout()));
chart.Append(new PlotVisibleOnly() { Val = new BooleanValue(true) });
chartPart.ChartSpace = chartSpace;
PositionChart(chartPart, drawingsPart, startRowIndex, startColumnIndex, endRowIndex, endColumnIndex);
}
Here's an additional method which will set chart position:
private static void PositionChart(ChartPart chartPart, DrawingsPart drawingsPart, int startRowIndex, int startColumnIndex, int endRowIndex, int endColumnIndex)
{
// Position the chart on the worksheet using a TwoCellAnchor object.
drawingsPart.WorksheetDrawing = new WorksheetDrawing();
TwoCellAnchor twoCellAnchor = drawingsPart.WorksheetDrawing.AppendChild<TwoCellAnchor>(new TwoCellAnchor());
twoCellAnchor.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.FromMarker(new ColumnId(startColumnIndex.ToString()),
new ColumnOffset("581025"),
new RowId(startRowIndex.ToString()),
new RowOffset("114300")));
twoCellAnchor.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.ToMarker(new ColumnId(endColumnIndex.ToString()),
new ColumnOffset("276225"),
new RowId(endRowIndex.ToString()),
new RowOffset("0")));
// Append a GraphicFrame to the TwoCellAnchor object.
DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame graphicFrame =
twoCellAnchor.AppendChild<DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame>(new DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame());
graphicFrame.Macro = "";
graphicFrame.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualGraphicFrameProperties(
new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualDrawingProperties() { Id = new UInt32Value(2u), Name = "Chart 1" },
new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualGraphicFrameDrawingProperties()));
graphicFrame.Append(new Transform(new Offset() { X = 0L, Y = 0L },
new Extents() { Cx = 0L, Cy = 0L }));
graphicFrame.Append(new Graphic(new GraphicData(new ChartReference() { Id = drawingsPart.GetIdOfPart(chartPart) })
{ Uri = "http://schemas.openxmlformats.org/drawingml/2006/chart" }));
twoCellAnchor.Append(new ClientData());
}
This method will add chart title:
private static void AddChartTitle(DocumentFormat.OpenXml.Drawing.Charts.Chart chart, string title)
{
var ctitle = chart.AppendChild(new Title());
var chartText = ctitle.AppendChild(new ChartText());
var richText = chartText.AppendChild(new RichText());
var bodyPr = richText.AppendChild(new BodyProperties());
var lstStyle = richText.AppendChild(new ListStyle());
var paragraph = richText.AppendChild(new Paragraph());
var apPr = paragraph.AppendChild(new ParagraphProperties());
apPr.AppendChild(new DefaultRunProperties());
var run = paragraph.AppendChild(new DocumentFormat.OpenXml.Drawing.Run());
run.AppendChild(new DocumentFormat.OpenXml.Drawing.RunProperties() { Language = "en-CA" });
run.AppendChild(new DocumentFormat.OpenXml.Drawing.Text() { Text = title });
//ctitle.AppendChild(new Overlay() { Val = new BooleanValue(false) });
}
My requirement is : Exporting a dynamic DataTable to Word document with Page Numbers
We need to use Open XML to achieve this.
I have code to export Datatable to Word. And also to insert page numbers.
I got Below code code to export datatable
public void CreateWordtable(string filename,DataTable data)
{
WordprocessingDocument doc = WordprocessingDocument.Create(filename, WordprocessingDocumentType.Document);
MainDocumentPart mainDocPart = doc.AddMainDocumentPart();
mainDocPart.Document = new Document();
Body body = new Body();
mainDocPart.Document.Append(body);
//rinks#::creating new table
DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table();
for (int i = 0; i < data.Rows.Count; ++i)
{
TableRow row = new TableRow();
for (int j = 0; j < data.Columns.Count; j++)
{
TableCell cell = new TableCell();
cell.Append(new Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(data.Rows[i][j].ToString()))));
cell.Append(new TableCellProperties(new TableCellWidth { Type = TableWidthUnitValues.Dxa, Width = "1200" }));
row.Append(cell);
}
table.Append(row);
}
body.Append(table);
doc.MainDocumentPart.Document.Save();
doc.Dispose();
}
And below code is to insert page numbers in a word document
private static void AddPageNumberFooters(WordprocessingDocument parent)
{
string documentPath = #"D:\EmptyDoc.docx";
using (WordprocessingDocument package =
WordprocessingDocument.Open(documentPath, true))
{
var mainDocumentPart = parent.AddMainDocumentPart();
GenerateMainDocumentPart().Save(mainDocumentPart);
var documentSettingsPart =
mainDocumentPart.AddNewPart
<DocumentSettingsPart>("rId1");
GenerateDocumentSettingsPart().Save(documentSettingsPart);
var firstPageFooterPart = mainDocumentPart.AddNewPart<FooterPart>("rId1");
GeneratePageFooterPart("Page 1 of 2").Save(firstPageFooterPart);
var secondPageFooterPart = mainDocumentPart.AddNewPart<FooterPart>("rId2");
GeneratePageFooterPart("Page 2 of 2").Save(secondPageFooterPart);
}
}
private static Document GenerateMainDocumentPart()
{
var element =
new Document(
new Body(
new Paragraph(
new Run(
new Text("Page 1 content"))
),
new Paragraph(
new Run(
new Break() { Type = BreakValues.Page })
),
new Paragraph(
new Run(
new LastRenderedPageBreak(),
new Text("Page 2 content"))
),
new Paragraph(
new Run(
new Break() { Type = BreakValues.Page })
),
new SectionProperties(
new FooterReference()
{
Type = HeaderFooterValues.First,
Id = "rId1"
},
new FooterReference()
{
Type = HeaderFooterValues.Even,
Id = "rId2"
},
new PageMargin()
{
Top = 1440,
Right = (UInt32Value)1440UL,
Bottom = 1440,
Left = (UInt32Value)1440UL,
Header = (UInt32Value)720UL,
Footer = (UInt32Value)720UL,
Gutter = (UInt32Value)0UL
},
new TitlePage()
)));
return element;
}
private static Header GeneratePageHeaderPart(string HeaderText)
{
var element =
new Header(
new Paragraph(
new ParagraphProperties(
new ParagraphStyleId() { Val = "Header" }),
new Run(
new Text(HeaderText))
));
return element;
}
My problem is, I have combine above both methods to export data along with page numbers.
if we know there are 2 pages in the word document, i can insert 2 FooterParts.
But i don't know how many pages will be created after exporting the data.
try the following code to automatically add page numbers:
private static string GenerateFooterPartContent(WordprocessingDocument package, string text = null)
{
FooterPart footerPart1 = package.MainDocumentPart.FooterParts.FirstOrDefault();
if (footerPart1 == null)
{
footerPart1 = package.MainDocumentPart.AddNewPart<FooterPart>();
}
var relationshipId = package.MainDocumentPart.GetIdOfPart(footerPart1);
// Get SectionProperties and set HeaderReference and FooterRefernce with new Id
SectionProperties sectionProperties1 = new SectionProperties();
FooterReference footerReference2 = new FooterReference() { Type = HeaderFooterValues.Default, Id = relationshipId };
sectionProperties1.Append(footerReference2);
package.MainDocumentPart.Document.Body.Append(sectionProperties1);
Footer footer1 = new Footer();
var r = new Run();
PositionalTab positionalTab2 = new PositionalTab() { Alignment = AbsolutePositionTabAlignmentValues.Right,
RelativeTo = AbsolutePositionTabPositioningBaseValues.Margin,
Leader = AbsolutePositionTabLeaderCharValues.None };
r.Append(positionalTab2);
paragraph2.Append(r);
r = new Run(new Text("Page: ") { Space = SpaceProcessingModeValues.Preserve },
// *** Adaptation: This will output the page number dynamically ***
new SimpleField() { Instruction = "PAGE" },
new Text(" of ") { Space = SpaceProcessingModeValues.Preserve },
// *** Adaptation: This will output the number of pages dynamically ***
new SimpleField() { Instruction = "NUMPAGES" });
paragraph2.Append(r);
footer1.Append(paragraph2);
footerPart1.Footer = footer1;
return relationshipId;
}
I am creating .xlsx file using open xml . When i try to read same file created using openxml it is not recognize properly. if I save my file again and try to read it, the problem goes away so I'm thinking it might be related to the way I have created the file. Any suggestions would be appreciated. Here's the code I'm using to generate my file.
public void CreatePackage(string filePath)
{
using (SpreadsheetDocument package = SpreadsheetDocument.Create(filePath, SpreadsheetDocumentType.Workbook))
{
CreateParts(package);
}
}
public void CreatePackage(MemoryStream mStream)
{
using (SpreadsheetDocument package = SpreadsheetDocument.Create(mStream, SpreadsheetDocumentType.Workbook))
{
CreateParts(package);
}
}
// Adds child parts and generates content of the specified part.
private void CreateParts(SpreadsheetDocument document)
{
ExtendedFilePropertiesPart extendedFilePropertiesPart1 = document.AddNewPart<ExtendedFilePropertiesPart>("rId3");
GenerateExtendedFilePropertiesPart1Content(extendedFilePropertiesPart1);
WorkbookPart workbookPart1 = document.AddWorkbookPart();
GenerateWorkbookPart1Content(workbookPart1);
WorksheetPart worksheetPart1 = workbookPart1.AddNewPart<WorksheetPart>("rId3");
GenerateWorksheetPart1Content(worksheetPart1);
WorksheetPart worksheetPart2 = workbookPart1.AddNewPart<WorksheetPart>("rId2");
GenerateWorksheetPart2Content(worksheetPart2);
WorksheetPart worksheetPart3 = workbookPart1.AddNewPart<WorksheetPart>("rId1");
GenerateWorksheetPart3Content(worksheetPart3);
SpreadsheetPrinterSettingsPart spreadsheetPrinterSettingsPart1 = worksheetPart3.AddNewPart<SpreadsheetPrinterSettingsPart>("rId1");
GenerateSpreadsheetPrinterSettingsPart1Content(spreadsheetPrinterSettingsPart1);
WorkbookStylesPart workbookStylesPart1 = workbookPart1.AddNewPart<WorkbookStylesPart>("rId5");
GenerateWorkbookStylesPart1Content(workbookStylesPart1);
//ThemePart themePart1 = workbookPart1.AddNewPart<ThemePart>("rId4");
//GenerateThemePart1Content(themePart1);
SetPackageProperties(document);
}
// Generates content of extendedFilePropertiesPart1.
private void GenerateExtendedFilePropertiesPart1Content(ExtendedFilePropertiesPart extendedFilePropertiesPart1)
{
Ap.Properties properties1 = new Ap.Properties();
properties1.AddNamespaceDeclaration("vt", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes");
Ap.Application application1 = new Ap.Application();
application1.Text = "Microsoft Excel";
Ap.DocumentSecurity documentSecurity1 = new Ap.DocumentSecurity();
documentSecurity1.Text = "0";
Ap.ScaleCrop scaleCrop1 = new Ap.ScaleCrop();
scaleCrop1.Text = "false";
Ap.HeadingPairs headingPairs1 = new Ap.HeadingPairs();
Vt.VTVector vTVector1 = new Vt.VTVector() { BaseType = Vt.VectorBaseValues.Variant, Size = (UInt32Value)2U };
Vt.Variant variant1 = new Vt.Variant();
Vt.VTLPSTR vTLPSTR1 = new Vt.VTLPSTR();
vTLPSTR1.Text = "Worksheets";
variant1.Append(vTLPSTR1);
Vt.Variant variant2 = new Vt.Variant();
Vt.VTInt32 vTInt321 = new Vt.VTInt32();
vTInt321.Text = "3";
variant2.Append(vTInt321);
vTVector1.Append(variant1);
vTVector1.Append(variant2);
headingPairs1.Append(vTVector1);
Ap.TitlesOfParts titlesOfParts1 = new Ap.TitlesOfParts();
Vt.VTVector vTVector2 = new Vt.VTVector() { BaseType = Vt.VectorBaseValues.Lpstr, Size = (UInt32Value)3U };
Vt.VTLPSTR vTLPSTR2 = new Vt.VTLPSTR();
vTLPSTR2.Text = "Sheet1";
Vt.VTLPSTR vTLPSTR3 = new Vt.VTLPSTR();
vTLPSTR3.Text = "Sheet2";
Vt.VTLPSTR vTLPSTR4 = new Vt.VTLPSTR();
vTLPSTR4.Text = "Sheet3";
vTVector2.Append(vTLPSTR2);
vTVector2.Append(vTLPSTR3);
vTVector2.Append(vTLPSTR4);
titlesOfParts1.Append(vTVector2);
Ap.Company company1 = new Ap.Company();
company1.Text = "PricewaterhouseCoopers";
Ap.LinksUpToDate linksUpToDate1 = new Ap.LinksUpToDate();
linksUpToDate1.Text = "false";
Ap.SharedDocument sharedDocument1 = new Ap.SharedDocument();
sharedDocument1.Text = "false";
Ap.HyperlinksChanged hyperlinksChanged1 = new Ap.HyperlinksChanged();
hyperlinksChanged1.Text = "false";
Ap.ApplicationVersion applicationVersion1 = new Ap.ApplicationVersion();
applicationVersion1.Text = "12.0000";
properties1.Append(application1);
properties1.Append(documentSecurity1);
properties1.Append(scaleCrop1);
properties1.Append(headingPairs1);
properties1.Append(titlesOfParts1);
properties1.Append(company1);
properties1.Append(linksUpToDate1);
properties1.Append(sharedDocument1);
properties1.Append(hyperlinksChanged1);
properties1.Append(applicationVersion1);
extendedFilePropertiesPart1.Properties = properties1;
}
// Generates content of workbookPart1.
private void GenerateWorkbookPart1Content(WorkbookPart workbookPart1)
{
Workbook workbook1 = new Workbook();
workbook1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
FileVersion fileVersion1 = new FileVersion() { ApplicationName = "xl", LastEdited = "4", LowestEdited = "4", BuildVersion = "4506" };
WorkbookProperties workbookProperties1 = new WorkbookProperties();
BookViews bookViews1 = new BookViews();
WorkbookView workbookView1 = new WorkbookView() { XWindow = 120, YWindow = 60, WindowWidth = (UInt32Value)15255U, WindowHeight = (UInt32Value)8160U };
bookViews1.Append(workbookView1);
//new line
//workbook1.Append(new BookViews(new WorkbookView()));
workbook1.Append(bookViews1);
Sheets sheets1 = new Sheets();
Sheet sheet1 = new Sheet() { Name = "Sheet1", SheetId = (UInt32Value)1U, Id = "rId1" };
Sheet sheet2 = new Sheet() { Name = "Sheet2", SheetId = (UInt32Value)2U, Id = "rId2" };
Sheet sheet3 = new Sheet() { Name = "Sheet3", SheetId = (UInt32Value)3U, Id = "rId3" };
sheets1.Append(sheet1);
sheets1.Append(sheet2);
sheets1.Append(sheet3);
CalculationProperties calculationProperties1 = new CalculationProperties() { CalculationId = (UInt32Value)125725U };
workbook1.Append(fileVersion1);
workbook1.Append(workbookProperties1);
workbook1.Append(sheets1);
workbook1.Append(calculationProperties1);
workbookPart1.Workbook = workbook1;
}
// Generates content of worksheetPart1.
private void GenerateWorksheetPart1Content(WorksheetPart worksheetPart1)
{
Worksheet worksheet1 = new Worksheet();
worksheet1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
SheetDimension sheetDimension1 = new SheetDimension() { Reference = "A1" };
SheetViews sheetViews1 = new SheetViews();
SheetView sheetView1 = new SheetView() { WorkbookViewId = (UInt32Value)0U };
sheetViews1.Append(sheetView1);
SheetFormatProperties sheetFormatProperties1 = new SheetFormatProperties() { DefaultRowHeight = 12.75D };
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 };
worksheet1.Append(sheetDimension1);
worksheet1.Append(sheetViews1);
worksheet1.Append(sheetFormatProperties1);
worksheet1.Append(sheetData1);
worksheet1.Append(pageMargins1);
worksheetPart1.Worksheet = worksheet1;
}
// Generates content of worksheetPart2.
private void GenerateWorksheetPart2Content(WorksheetPart worksheetPart2)
{
Worksheet worksheet2 = new Worksheet();
worksheet2.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
SheetDimension sheetDimension2 = new SheetDimension() { Reference = "A1" };
SheetViews sheetViews2 = new SheetViews();
SheetView sheetView2 = new SheetView() { WorkbookViewId = (UInt32Value)0U };
sheetViews2.Append(sheetView2);
SheetFormatProperties sheetFormatProperties2 = new SheetFormatProperties() { DefaultRowHeight = 12.75D };
SheetData sheetData2 = new SheetData();
PageMargins pageMargins2 = new PageMargins() { Left = 0.7D, Right = 0.7D, Top = 0.75D, Bottom = 0.75D, Header = 0.3D, Footer = 0.3D };
worksheet2.Append(sheetDimension2);
worksheet2.Append(sheetViews2);
worksheet2.Append(sheetFormatProperties2);
worksheet2.Append(sheetData2);
worksheet2.Append(pageMargins2);
worksheetPart2.Worksheet = worksheet2;
}
private void GenerateWorksheetPart3Content(WorksheetPart worksheetPart3)
{
Worksheet worksheet3 = new Worksheet();
worksheet3.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
SheetDimension sheetDimension3 = new SheetDimension() { Reference = "A1" };
SheetViews sheetViews3 = new SheetViews();
SheetView sheetView3 = new SheetView() { TabSelected = true, WorkbookViewId = (UInt32Value)0U };
sheetViews3.Append(sheetView3);
SheetFormatProperties sheetFormatProperties3 = new SheetFormatProperties() { DefaultRowHeight = 12.75D };
Columns columns1 = new Columns();
Column column1 = new Column() { Min = (UInt32Value)1U, Max = (UInt32Value)52U, Width = 20.7109375D, CustomWidth = true };
columns1.Append(column1);
SheetData sheetData3 = new SheetData();
Row row1 = new Row() { RowIndex = (UInt32Value)1U, Spans = new ListValue<StringValue>() { InnerText = "1:1" } };
Cell cell1 = new Cell() { CellReference = "A1", StyleIndex = (UInt32Value)1U };
row1.Append(cell1);
sheetData3.Append(row1);
/*
Row row2 = new Row() { RowIndex = (UInt32Value)2U, Spans = new ListValue<StringValue>() { InnerText = "1:1" } };
Cell cell2 = new Cell() { CellReference = "B2", StyleIndex = (UInt32Value)1U };
row2.Append(cell2);
sheetData3.Append(row2);
Row row3 = new Row() { RowIndex = (UInt32Value)3U, Spans = new ListValue<StringValue>() { InnerText = "1:1" } };
Cell cell3 = new Cell() { CellReference = "C3", StyleIndex = (UInt32Value)2U };
row3.Append(cell3);
sheetData3.Append(row3);
*/
PageMargins pageMargins3 = 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" };
worksheet3.Append(sheetDimension3);
worksheet3.Append(sheetViews3);
worksheet3.Append(sheetFormatProperties3);
worksheet3.Append(columns1);
worksheet3.Append(sheetData3);
worksheet3.Append(pageMargins3);
worksheet3.Append(pageSetup1);
worksheetPart3.Worksheet = worksheet3;
}
// Generates content of worksheetPart3.
private void GenerateWorksheetPart3ContentNew(WorksheetPart worksheetPart3)
{
Worksheet worksheet3 = new Worksheet();
worksheet3.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
SheetDimension sheetDimension3 = new SheetDimension() { Reference = "A1" };
SheetViews sheetViews3 = new SheetViews();
SheetView sheetView3 = new SheetView() { TabSelected = true, WorkbookViewId = (UInt32Value)0U };
sheetViews3.Append(sheetView3);
SheetFormatProperties sheetFormatProperties3 = new SheetFormatProperties() { DefaultRowHeight = 12.75D };
Columns columns1 = new Columns();
Column column1 = new Column() { Min = (UInt32Value)1U, Max = (UInt32Value)52U, Width = 20.7109375D, CustomWidth = true };
columns1.Append(column1);
string[] cellname = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
SheetData sheetData3 = new SheetData();
int counter = 1;
Row row1 = new Row() { RowIndex = (UInt32Value)1U, Spans = new ListValue<StringValue>() { InnerText = "1:1" } };
Cell cell1 = new Cell() { CellReference = "A1", StyleIndex = (UInt32Value)1U };
row1.Append(cell1);
sheetData3.Append(row1);
/*
int counter = 1;
Row row1 = new Row() { RowIndex = (UInt32Value)1U, Spans = new ListValue<StringValue>() { InnerText = "1:1" } };
foreach (string cell in cellname)
{
string cellId = cell + counter;
Cell cell1 = new Cell() { CellReference = cellId, StyleIndex = (UInt32Value)1U };
row1.Append(cell1);
}
sheetData3.Append(row1);
*/
/*
Row row1 = new Row() { RowIndex = (UInt32Value)1U, Spans = new ListValue<StringValue>() { InnerText = "1:1" } };
string[] cellname = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
Cell cell1 = new Cell() { CellReference = "A1", StyleIndex = (UInt32Value)2U };
row1.Append(cell1);
Cell cell12 = new Cell() { CellReference = "B1", StyleIndex = (UInt32Value)2U };
row1.Append(cell12);
Cell cell13 = new Cell() { CellReference = "C1", StyleIndex = (UInt32Value)2U };
row1.Append(cell13);
//Cell cell21 = new Cell() { CellReference = "A2", StyleIndex = (UInt32Value)2U };
//Cell cell31 = new Cell() { CellReference = "A3", StyleIndex = (UInt32Value)2U };
//Cell cell41 = new Cell() { CellReference = "A4", StyleIndex = (UInt32Value)2U };
//row1.StyleIndex = (UInt32Value)2U;
//row1.Append(cell21);
//row1.Append(cell31);
//row1.Append(cell41);
sheetData3.Append(row1);
*/
counter = 2;
Row row2 = new Row() { RowIndex = (UInt32Value)2U, Spans = new ListValue<StringValue>() { InnerText = "1:1" } };
Cell cell2 = new Cell() { CellReference = "B2", StyleIndex = (UInt32Value)1U };
row2.Append(cell2);
sheetData3.Append(row2);
counter = 3;
Row row3 = new Row() { RowIndex = (UInt32Value)3U, Spans = new ListValue<StringValue>() { InnerText = "1:1" } };
Cell cell3 = new Cell() { CellReference = "C3", StyleIndex = (UInt32Value)2U };
row3.Append(cell3);
sheetData3.Append(row3);
counter = 4;
Row row4 = new Row() { RowIndex = (UInt32Value)4U, Spans = new ListValue<StringValue>() { InnerText = "1:1" } };
Cell cell4 = new Cell() { CellReference = "D4", StyleIndex = (UInt32Value)2U };
row4.Append(cell4);
sheetData3.Append(row4);
counter = 5;
Row row5 = new Row() { RowIndex = (UInt32Value)5U, Spans = new ListValue<StringValue>() { InnerText = "1:1" } };
foreach (string cell in cellname)
{
string cellId = cell + counter;
Cell cell5 = new Cell() { CellReference = cellId, StyleIndex = (UInt32Value)2U };
row5.Append(cell5);
}
sheetData3.Append(row5);
counter = 6;
Row row6 = new Row() { RowIndex = (UInt32Value)6U, Spans = new ListValue<StringValue>() { InnerText = "1:1" } };
Cell cell6 = new Cell() { CellReference = "F6", StyleIndex = (UInt32Value)1U };
row6.Append(cell6);
sheetData3.Append(row6);
counter = 7;
Row row7 = new Row() { RowIndex = (UInt32Value)7U, Spans = new ListValue<StringValue>() { InnerText = "1:1" } };
Cell cell7 = new Cell() { CellReference = "G7", StyleIndex = (UInt32Value)1U };
row7.Append(cell7);
sheetData3.Append(row7);
PageMargins pageMargins3 = 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" };
worksheet3.Append(sheetDimension3);
worksheet3.Append(sheetViews3);
worksheet3.Append(sheetFormatProperties3);
worksheet3.Append(columns1);
worksheet3.Append(sheetData3);
worksheet3.Append(pageMargins3);
worksheet3.Append(pageSetup1);
worksheetPart3.Worksheet = worksheet3;
}
Here is code i am using to read excel file
public static DataTable ExtractExcelToDataTable(Stream filename)
{
DataTable dt = new DataTable();
string value = string.Empty;
//MemoryStream stream = new MemoryStream();
//stream.Write(filename1, 0, filename1.Length);
try
{
using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(filename, false))
//using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(stream, false))
{
/*
WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
string relationshipId = sheets.First().Id.Value;
WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);
Worksheet workSheet = worksheetPart.Worksheet;
*/
WorkbookPart workbook = spreadSheetDocument.WorkbookPart;
//create a reference to Sheet1
WorksheetPart workSheet = workbook.WorksheetParts.Last();
SheetData sheetData = workSheet.Worksheet.GetFirstChild<SheetData>();
//SheetData sheetData = workSheet.GetFirstChild<SheetData>();
IEnumerable<Row> rows = sheetData.Descendants<Row>();
int RowIndex = 0;
foreach (var row in rows)
{
//Create the data table header row ie columns using first excel row.
if (RowIndex == 0)
{
//CreateColumnsFromHeaderRow(row, dt);
foreach (Cell cell in rows.ElementAt(0))
{
dt.Columns.Add(GetCellValue(spreadSheetDocument, cell));
}
RowIndex++;
}
else
{
//From second row of excel onwards, add data rows to data table.
IEnumerable<Cell> cells = GetCellsFromRowIncludingEmptyCells(row);
DataRow newDataRow = dt.NewRow();
int columnCount = 0;
foreach (Cell currentCell in cells)
{
value = GetCellValue(spreadSheetDocument, currentCell);
//There are empty headers which are not added to data table columns. So avoid those.
if (columnCount < dt.Columns.Count)
{
newDataRow[columnCount++] = value;
}
}
dt.Rows.Add(newDataRow);
}
}
//dt.Rows.RemoveAt(0);
//remove empty rows
//DataTable filteredDataTable = (dt.Rows.Cast<DataRow>().Where(row => row.ItemArray.Any(field => !(field is DBNull)))).CopyToDataTable<DataRow>();
DataTable filteredDataTable = new DataTable();
if (dt != null && dt.Rows.Count > 0)
{
filteredDataTable = (dt.Rows.Cast<DataRow>().Where(row => row.ItemArray.Any(field => (field.ToString() != string.Empty && field != null)))).CopyToDataTable<DataRow>();
}
return filteredDataTable;
}
}
catch (Exception ex)
{
throw ex;
}
}
public static string GetCellValue(SpreadsheetDocument document, Cell cell)
{
SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart;
string value = string.Empty;
if (cell != null)
{
if (cell.CellValue != null)
{
value = cell.CellValue.InnerXml;
if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
{
value = stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
//Remove new line character
value = value.Replace("\n", "").Trim();
}
}
}
return value;
}