How to Convert Table into a Normal Range of cells while exporting excel in c# - range

How to Convert Table into a Normal Range of cells while exporting excel in c#.
By default it is in Table format, not able to sort due to tabel format. I need this to normal range of cells.
After excel exported, you able to do in manually by selecting Table tools (design) and have option to select "convert to range". I need to done via code by using closedXML.
System.Data.DataTable dataTable = magicButtonApi.ExportData(magicButtonCheckedNodesBE);
var fileName = "Excel_" + DateTime.Now.ToString("yyyyMMddHHmm") + ".xlsx";
//save the file to server temp folder
string fullPath = Path.Combine(Server.MapPath("~/temp"), fileName);
using (MemoryStream stream = new MemoryStream())
{
// Start a new workbook
XLWorkbook wb = new XLWorkbook();
// Add a DataTable as a worksheet
var ws = wb.Worksheets.Add(dataTable, "MagicButton");
//wb.SaveAs(stream, false);
wb.SaveAs(fullPath);
return Json(new { fileName = fullPath, errorMessage = "" });
// Return a byte array
//return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "YourReportName.xlsx");
}

wb.Worksheets.Tables.Remove(dataTable.Name);

Related

How to create an Excel file and it by Email, using code x++ in Dynamics AX2012?

I need to create an Excel file and to send it by Email, by X++ code in to Dyncamics AX2012.
If it's possible I don't want to save the data in a physical path/folder.
I wrote this code, but after I need to send the Excel.
I would like to follow the D365 instructions (https://axexplorer.wordpress.com/2017/07/18/create-an-excel-file-and-send-it-through-e-mail-in-d365-for-operationax-7/ )in Dynamics AX 2012 (In AX2012 some command are not available)
SysEmailParameters parameters = SysEmailParameters::find();
SMTPRelayServerName relayServer;
SMTPPortNumber portNumber;
SMTPUserName userName;
SMTPPassword password;
Str1260 subject,body;
InteropPermission interopPermission;
SysMailerMessageBuilder mailer;
SysMailerAttachments attach;
System.Exception e;
SysExcelApplication application;
SysExcelWorkbooks workbooks;
SysExcelWorkbook workbook;
SysExcelWorksheets worksheets;
SysExcelWorksheet worksheet;
SysExcelCells cells;
SysExcelCell cell;
int row;
str contact;
int recordscount;
MYTABLE myTable;
System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
row = 1 ;
mailer.subject("MY subject");
mailer.fromAddress("MY_from#com");
mailer.htmlBody("MY_BODY");
mailer.tos().appendAddress("MY_to.com");
application = SysExcelApplication::construct();
workbooks = application.workbooks();
workbook = workbooks.add();
worksheets = workbook.worksheets();
worksheet = worksheets.itemFromNum(1);
cells = worksheet.cells();
//cells.range(‘A:A’).numberFormat(‘#’);
cell = cells.item(1,1);
cell.value("Field_I");
cell = cells.item(1,2);
cell.value("Field_II");
while select myTable
{
row++;
cell = cells.item(row, 1);
cell.value(myTable.Field_I);
cell = cells.item(row, 2);
cell.value(myTable.Field_I);
}
application.visible(true);
application.save();
memoryStream.Seek(0, System.IO.SeekOrigin::Begin);
I'm not able to save the file in temporary stream.
In AX2012 are not available the
SysMailerMessageBuilder mailer = new SysMailerMessageBuilder();;
var package = new OfficeOpenXml.ExcelPackage(memoryStream)
//The below line used to attach excel file to email.
mailer.addAttachment(memoryStream, ‘MYFILE.xlsx’, ‘application/vnd.openxmlformats-officedocument.spreadsheetml.sheet’);
There is any way in Dynamics AX2012 to create an excel file and send the file to email (withouth saving in to the path).
Thanks in advance.
Following the #Alex Kwitny kind comment, I used this code:
#Properties
#AOT
#File
#define.io_rw("rw")
Filename filename;
str tempPath;
FileIOPermission fileIOPermission;
if(_runOnService)
{
fileIOPermission = new FileIOPermission('','r');
fileIOPermission.assert();
tempPath = WinAPIServer::getTempPath();
CodeAccessPermission::revertAssert();
filename = tempPath + _name + #xml;
}
else
{
tempPath = WinAPI::getTempPath();
filename = tempPath + _name + #xml;
}
tempPath = WinAPI::getTempPath();
tempPath = WinAPIServer::getTempPath();
Thanks all.

How can we write data to excel Template and maintain the template format in OpenXML?

I am able to read the excel template using openxml, and able to append data to the sheets.
But unable to maintain the existing Excel Template format, and unable to identify the column headings
Please find the below code used
if (ds.Tables.Count > 0 && ds.Tables[0] != null || ds.Tables[0].Columns.Count > 0)
{
System.Data.DataTable table = ds.Tables[0];
using (var spreadsheetDocument = SpreadsheetDocument.Open(filePath, true))
{
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
Sheet sheet = spreadsheetDocument.WorkbookPart.Workbook.Sheets.GetFirstChild<Sheet>();
Worksheet worksheet = (spreadsheetDocument.WorkbookPart.GetPartById(sheet.Id.Value) as WorksheetPart).Worksheet;
SheetData sheetData = worksheet.GetFirstChild<SheetData>();
List<String> columns = new List<string>();
IEnumerable<Row> rows = worksheet.GetFirstChild<SheetData>().Descendants<Row>();
foreach (DataColumn column in table.Columns)
{
columns.Add(column.ColumnName);
Cell cell = new Cell();
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(column.ColumnName);
}
foreach (DataRow row in table.Rows)
{
Row newRow = new Row();
columns.ForEach(col =>
{
Cell cell = new Cell();
//If value is DBNull, do not set value to cell
if (row[col] != System.DBNull.Value)
{
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(row[col].ToString());
}
newRow.AppendChild(cell);
});
sheetData.AppendChild(newRow);
}
spreadsheetDocument.WorkbookPart.Workbook.Save();
spreadsheetDocument.Close();
}
Please find actual excel screenshot
please find expected excel screenshot
Please clarify your specific problem and provided the actual code snippet and the example template that you are using so we can better understand your issue and assist you on the issue.
There is earlier post “OpenXML SDK 2.5 Excel Template" Find a label in template with name DataField, and replace with data. This might be what you are looking for.

How to read the data from Excel sheet and print the result on console while working on protractor

I am working on AngularJs application testing framework where I am using Protractor. I want to read the data (urls, usernames, passwords) from an excel sheet. I am using the following code but it's showing me errors.
Please find the below code:
var Excel = require('exceljs');
var wrkbook = new Excel.Workbook();
wrkbook.xlsx.readFile('E:\\Login_Data.xlsx').then(function()
{
var worksheet = wrkbook.getWorksheet('Sheet1');
worksheet.eachRow(function (Row, Test_URL)
{
console.log("Row " + Test_URL + " = " + JSON.stringify(Row.User_Name));
});
});
The data from excel sheet is :
Test_URL User_Name Password
http://...com abc#1111 xyz#333
Please let me know your positive inputs so that I can run my code and proceed forward.
Thanks in advance
eachRow isn't getting the Test_URL variable that you set as function parameter; that is instead the row index.
For getting every value of the row, you can use Row.values, and also you could the value of each Cell (corresponding to that row) with .getCell.
So it should be something like this:
var Excel = require('exceljs');
var wrkbook = new Excel.Workbook();
wrkbook.xlsx.readFile('E:\\Login_Data.xlsx').then(function()
{
var worksheet = wrkbook.getWorksheet('Sheet1');
worksheet.eachRow(function (Row, rowIndex)
{
var test_url = Row.getCell(1).value;
var user_name = Row.getCell(2).value;
var password = Row.getCell(3).value;
// do whatever you want with those variables.
});
});

Programmatically create Infopath form in SharePoint form library with dates

I am programmatically creating InfoPath forms in a form library within SharePoint 2010 from data in a CSV file. It all works fine apart from the date fields. The form will refuse to open with a format error. I have tried multiple ways of formatting the date but no luck so far. Code below...
If I format 2016-10-10 then it does show in the Forms Library view but I still can not open the form. It just shows a datatype error.
// Get the data from CSV file.
string[,] values = LoadCsv("ImportTest.csv");
//Calulate how many columns and rows in the dataset
int countCols = values.GetUpperBound(1) + 1;
int countRows = values.GetUpperBound(0) + 1;
string rFormSite = "siteurl";
// opens the site
SPWeb webSite = new SPSite(rFormSite).OpenWeb();
// gets the blank file to copy
SPFile BLANK = webSite.Folders["EventSubmissions"].Files["Blank.xml"];
// reads the blank file into an xml document
MemoryStream inStream = new MemoryStream(BLANK.OpenBinary());
XmlTextReader reader = new XmlTextReader(inStream);
XmlDocument xdBlank = new XmlDocument();
xdBlank.Load(reader);
reader.Close();
inStream.Close();
//Get latest ID from the list
int itemID = GetNextID(webSite, "EventSubmissions");
if (itemID == -1) return;
//Iterate each row of the dataset
for (int row = 1; row < countRows; row++)
{
//display current event name
Console.WriteLine("Event name - " + values[row, 4]);
XmlDocument xd = xdBlank;
XmlElement root = xd.DocumentElement;
//Cycling through all columns of the document//
for (int col = 0; col < countCols; col++)
{
string field = values[0, col];
string value = values[row, col];
switch (field)
{
case "startDate":
value = //How do format the date here ;
break;
case "endDate":
value = "";
break;
case "AutoFormID":
value = itemID.ToString();
break;
}
XmlNodeList nodes = xd.GetElementsByTagName("my:" + field);
foreach (XmlNode node in nodes)
{
node.InnerText = value;
}
}
// saves the XML Document back as a file
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
SPFile newFile = webSite.Folders["EventSubmissions"].Files.Add(itemID.ToString() + ".xml", (encoding.GetBytes(xd.OuterXml)), true);
itemID++;
}
Console.WriteLine("Complete");
Console.ReadLine();
Thanks
For me this worked
DateTime.Now.ToString("yyyy-MM-dd")

Create doc file from template and adding data from database using open xml

I have a word template and I want to create doc file from that, also I want to replace add data in place of bookmarks present in the template.
I have been able to create a doc file, but I am not able to understand, how to add data in place of bookmarks?
My code till now:
private void CreateSampleWordDocument()
{
string sourceFile = Path.Combine(Environment.CurrentDirectory, "GeneralWelcomeLetter.dotx");
string destinationFile = Path.Combine(Environment.CurrentDirectory, "Sample.docx");
try
{
File.Copy(sourceFile, destinationFile, true);
WordprocessingDocument document = WordprocessingDocument.Open(destinationFile, true);
document.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
MainDocumentPart mainPart = document.MainDocumentPart;
DocumentSettingsPart documentSettingPart1 = mainPart.DocumentSettingsPart;
AttachedTemplate attachedTemplate1 = new AttachedTemplate() { Id = "relationId1" };
documentSettingPart1.Settings.Append(attachedTemplate1);
}
catch
{
}
}
Now to add data from database in place of bookmarks?