I woulld like to create then add 2 files into same file as attachment.
How can i do that? Please find below what i tried so far.
Excel files comes from resource/files and TXT file is just created during document saving progress.
importPackage(org.apache.poi.ss.usermodel);
var resourcePath = "/SampleExcelFile.xlsx";
var bantfile = java.lang.System.getProperty("java.io.tmpdir");
var srtEk = "FileName1";
var excelName = srtEk + ".xlsx";
var textFileName = srtEk + +".txt";
var excelFilePath = bantfile+"\\"+ excelName;
var ledesFilePath = bantfile+"\\"+ textFileName;
var inp = facesContext.getExternalContext().getResourceAsStream(resourcePath);
var wb = WorkbookFactory.create(inp);
var sheet = wb.getSheetAt(0);
var row = sheet.getRow(2);
if (row == null)
{
row = sheet.createRow(2);
}
var cell = row.getCell(0);
if (cell == null)
{
cell = row.createCell(0);
}
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(tempFilePath);
var fileOut = new java.io.FileOutputStream(excelFilePath);
wb.write(fileOut);
fileOut.close();
var fileOut = new java.io.FileOutputStream(ledesFilePath);
wb.write(fileOut);
fileOut.close();
var doc = database.createDocument();
doc.replaceItemValue("Form", "frmTest");
var rtitem = doc.createRichTextItem("Body");
rtitem.embedObject(lotus.domino.local.EmbeddedObject.EMBED_ATTACHMENT, null, excelFilePath , null);
doc.save(true, false);
You can add as much attachments to a RichText field as you like.
Just add another embedObject line to your code:
rtitem.embedObject(lotus.domino.local.EmbeddedObject.EMBED_ATTACHMENT, null, ledesFilePath, null);
Related
I have an Excel file with one sheet and one chart. I am trying to copy this chart and paste it on a new Word document using OpenXml SDK. I do not want an image of the chart, but an editable chart object, not referenced to the Excel file.
This is what I tried:
using (SpreadsheetDocument document = SpreadsheetDocument.Open("Test1.xlsx", true))
{
var bkPart = document.WorkbookPart;
var workbook = bkPart.Workbook;
var s = workbook.Sheets.FirstOrDefault();
var wsPart = bkPart.WorksheetParts.FirstOrDefault();
var dp = wsPart.DrawingsPart;
var dWs = dp.WorksheetDrawing;
var cp = dp.ChartParts.FirstOrDefault();
var plotArea = cp.ChartSpace.Descendants<PlotArea>().FirstOrDefault();
using (var docx = WordprocessingDocument.Open("Test1.docx", true))
{
docx.MainDocumentPart.Document.Body.RemoveAllChildren();
var cpw = docx.MainDocumentPart.AddPart(cp);
var p = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
var r = new Run();
var d = new Drawing();
var i = new Inline();
var g = new Graphic();
var gd = new GraphicData();
var c = new DocumentFormat.OpenXml.Drawing.Charts.Chart();
docx.MainDocumentPart.Document.Body.Append(p);
p.Append(r);
r.Append(d);
d.Append(i);
i.Append(g);
g.Append(gd);
gd.Append(c);
// I am stuck here
}
}
I tried to take the ChartPart from Excel and adding it to the Word document and then to create a new chart referencing the inserted new ChartPart. Unfortunately, I am stuck on this step. How can I get and use this reference to create the chart? Otherwise is there another way to copy a chart from Excel to Word?
Thanks in advance.
I found this workaround to copy a chart from Excel to Word:
Create a new ChartPart on the Word document.
Add to this ChartPart a ChartSpace cloned from Excel.
Add a new chart to the Word document referencing the new ChartPart.
This is the code:
using (SpreadsheetDocument document = SpreadsheetDocument.Open("Test1.xlsx", true))
{
var bkPart = document.WorkbookPart;
var workbook = bkPart.Workbook;
var s = workbook.Sheets.FirstOrDefault();
var wsPart = bkPart.WorksheetParts.FirstOrDefault();
var dp = wsPart.DrawingsPart;
var dWs = dp.WorksheetDrawing;
var cp = dp.ChartParts.FirstOrDefault();
using (var docx = WordprocessingDocument.Open("Test1.docx", true))
{
MainDocumentPart mainPart = docx.MainDocumentPart;
ChartPart chartPart = mainPart.AddNewPart<ChartPart>("rId777");
chartPart.ChartSpace = (ChartSpace)cp.ChartSpace.Clone();
var paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph() { RsidParagraphAddition = "00C75AEB", RsidRunAdditionDefault = "000F3EFF" };
Run run = new Run();
Drawing drawing = new Drawing();
Inline inline = new Inline();
inline.Append(new Extent() { Cx = 5274310L, Cy = 3076575L });
DocProperties docPros = new DocProperties() { Id = (UInt32Value)1U, Name = "Chart7" };
inline.Append(docPros);
Graphic g = new Graphic();
var graphicData = new GraphicData() { Uri = "http://schemas.openxmlformats.org/drawingml/2006/chart" };
var chartReference = new ChartReference() { Id = "rId777" };
graphicData.Append(chartReference);
g.Append(graphicData);
inline.Append(g);
drawing.Append(inline);
run.Append(drawing);
paragraph.Append(run);
mainPart.Document.Body.Append(paragraph);
}
}
I'm trying to generate an excel file / stream in my web api and return it in a HttpResponseMessage to serve it to the client in Angular 5 as a download.
The generation succeeds and an xlsx file is generated and saved on the server, but when I return it in the Content of my httpResponseMessage, my browser shows just some json instead of the whole excel file.
{"version":{"major":1,"minor":1,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-1},"content":{"headers":[{"key":"Content-Disposition","value":["attachment; filename=636742856488421817.xlsx"]},{"key":"Content-Type","value":["application/ms-excel"]},{"key":"Content-Length","value":["22780"]}]},"statusCode":200,"reasonPhrase":"OK","headers":[],"requestMessage":null,"isSuccessStatusCode":true}
This is how I create the excel file and returns it:
var dataBytes = File.ReadAllBytes(fileName);
var dataStream = new MemoryStream(dataBytes);
HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
httpResponseMessage.Content = new StreamContent(dataStream);
httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
httpResponseMessage.Content.Headers.ContentDisposition.FileName = fileName;
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/ms-excel");
httpResponseMessage.Content.Headers.ContentLength = dataStream.Length;
I solved this:
Here is what I did
Helper class which creates the excel package and converts it to a Stream
var fileName = DateTime.Now.Ticks + ".xlsx";
FileInfo file = new FileInfo(fileName);
FileInfo templateFile = new FileInfo(#"Templates/ReportTemplate.xlsx");
ExcelPackage package = new ExcelPackage(file, templateFile);
ExcelWorksheet worksheet = package.Workbook.Worksheets.FirstOrDefault();
... filling rows and cells goed here ...
var dataBytes = package.GetAsByteArray();
Stream dataStream = new MemoryStream(dataBytes);
dataStream.Seek(0, SeekOrigin.Begin);
return dataStream;
In the controller I return the file to the Angular client like this:
var stream = _helperClass.GenerateReport(exportDate, exportTitle);
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", $"Report-{DateTime.Now.ToShortDateString()}.xlsx");
In the Angular component I do this after I receive the response:
var blob = new Blob([res], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
var blobURL = window.URL.createObjectURL(blob);
var anchor = document.createElement("a");
anchor.download = `Report-${new Date().toISOString()}.xlsx`;
anchor.href = blobURL;
anchor.click();
Try this following code:
For conroller:
[Route("DownLoadExcel")]
public IActionResult DownLoadExcel()
{
var pack = new ExcelPackage();
ExcelWorksheet worksheet = pack.Workbook.Worksheets.Add("sample");
//First add the headers
worksheet.Cells[1, 1].Value = "ID";
worksheet.Cells[1, 2].Value = "Name";
//Add values
worksheet.Cells["A2"].Value = 1000;
worksheet.Cells["B2"].Value = "Jon";
return File(pack.GetAsByteArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Sample.xlsx");
}
For client side:
window.open("../.../DownLoadExcel");
How could we get all script name and script id in array I want it to be shown in dropdown in my application.
Here is my code which is only giving me filename I am not getting external url like this
https://4512314-sb1.restlets.api.netsuite.com/app/site/hosting/restlet.nl?script=692&deploy=1
here is my code
function searchScriptFile()
{
var folderid = 'SuiteScripts';
var filters = new Array();
filters[0] = new nlobjSearchFilter('name', null, 'is', folderid);
var columns = new Array();
var filename = new nlobjSearchColumn('name', 'file');
var fileid = new nlobjSearchColumn('internalid', 'file');
var path = new nlobjSearchColumn('url', 'file');
columns[0] = filename;
columns[1] = fileid;
columns[2] = path;
var searchResult = nlapiSearchRecord('folder', null , filters , columns);
var res = new Array();
if(searchResult) {
for (var i = 0 ; i < searchResult.length; i++) {
thisfile = searchResult[i].getValue(filename);
thisfileid = searchResult[i].getValue(fileid);
thispath = searchResult[i].getValue(path);
res[i] = thisfile + ' ' + thisfileid + ' ' + thispath;
nlapiLogExecution('DEBUG', 'Test', thisfileid + ' ' + thisfile);
}
return res[27];
}
}
You need to search for the script deployments, not the files in the file cabinet.
var scriptdeploymentSearch = nlapiSearchRecord("scriptdeployment",null,
[
],
[
new nlobjSearchColumn("title").setSort(false),
new nlobjSearchColumn("scriptid"),
new nlobjSearchColumn("script"),
new nlobjSearchColumn("scriptid","script",null),
new nlobjSearchColumn("recordtype"),
new nlobjSearchColumn("status"),
new nlobjSearchColumn("isdeployed"),
new nlobjSearchColumn("scripttype"),
new nlobjSearchColumn("ismobilemenu"),
new nlobjSearchColumn("apiversion","script",null)
]
);
You need to run search on scriptdeployment(as suggested above by dcrs) and not on folder. Although I didn't find any way to fetch externalurl of the script-deployement, guess NetSuite doesn't support it yet.
Here is the basic code to on ScriptDeploymemts though
search.create({
type: 'scriptdeployment',
columns: ['script.scriptfile', 'title',
'scriptid', 'script.apiversion']
}).run().getRange({ start: 0, end: 1000 });
New to MVC and having some trouble with what should be simple. I'm trying to return a dataset to just an Excel spreadsheet without any real UI.
Here's my code (cannibalized from a few sources):
Controller code:
public ActionResult GetCommissionsExcel(string agencyid, string month, string year)
{
try
{
var as400rep = new iSeriesRepository(new iSeriesContext());
var results = as400rep.GetCommissionExcel(agencyid, month, year);
string xml = String.Empty;
XmlDocument xmlDoc = new XmlDocument();
XmlSerializer xmlSerializer = new XmlSerializer(results.GetType());
using (System.IO.MemoryStream xmlStream = new System.IO.MemoryStream())
{
xmlSerializer.Serialize(xmlStream, results);
xmlStream.Position = 0;
xmlDoc.Load(xmlStream);
xml = xmlDoc.InnerXml;
}
var fName = string.Format("CommissionsExcelExport-{0}", DateTime.Now.ToString("s"));
byte[] fileContents = System.Text.Encoding.UTF8.GetBytes(xml);
return File(fileContents, "application/vnd.ms-excel", fName);
}
catch (Exception ex)
{
Log.Error(ex.Message, ex.InnerException);
throw;
}
}
The jQuery call:
function getExcelExport() {
var activePane = $('div.tab-pane.active');
var agencyCompany = $(activePane).find('#Agency_AgencyId').val();
var month = $(activePane).find('#CommissionMonth').val();
var year = $(activePane).find('#CommissionYear').val();
var url = '#Url.Content("~")' + 'AgencyManagement/GetCommissionsExcel';
window.location = 'AgencyManagement/GetCommissionsExcel';
//$.post('#Url.Action("GetCommissionsExcel", "AgencyManagement")' , {agencyid: agencyCompany, month: month, year: year});
};
It pulls back the data, but I can't figure out how to get it to pop from the search window. It looks like the window.location line makes the call, but I need to post the parameters to the call and that's where I'm stuck.
Figured it out. Just needed to call the jQuery as follows:
window.location = 'AgencyManagement/GetCommissionsExcel?agencyID=' + agencyCompany + '&month=' + month + '&year=' + year;
And I needed to append ".xls" to the filename in the controller action.
var fName = string.Format("CommissionsExcelExport-{0}", DateTime.Now.ToString("s"));
fName = fName + ".xls";
Worked like a charm
i want to return all data to txt file from my csv
string fileName = "../../TechFiles/";
List<string> listA = new List<string>();
using (var reader = new StreamReader(ConfigurationManager.AppSettings["ConfigurationSource"]))
{
var hdr2 = "2012-05-09 12:52:00";
var hdr1 = "Account";
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
listA.Add(values[0]);
csv = new StringBuilder();
newLine = string.Format("HDR {0} {1}\r\n{2}{3}" , hdr1,line, Environment.NewLine);
csv.Append(newLine);
File.WriteAllText(String.Format("{0}{1}", fileName, values[4] + ".txt"), csv.ToString());
}
}
Use File.AppendAllText:
File.AppendAllText(String.Format("{0}{1}", fileName, values[4] + ".txt"), csv.ToString());