Converting from HWPFDocument to XWPFDocument or vice versa - apache-poi

I have a Word document, where I have to replace text and save this document in Oracle database, in PDF format. Have someone any idea how to resolve this?
String inputFilename = "/root/GeneratorUmow/web/WEB-INF/umowy/kkb/wniosekozaciag.docx";
try(InputStream is = new FileInputStream(inputFilename)) {
dbd = new DokumentyBlobDAO();
db.setNazwaPliku("Wniosek_o_zaciagniecie.pdf");
db.setTypDokuemntu(876990);
if(du.getTypKlienta() == S_ID_Lead_Partner_Typ_Klienta_KKB) {
POIFSFileSystem fs = null;
fs = new POIFSFileSystem(is);
HWPFDocument doc = new HWPFDocument(fs); //funkcja zamyka inputstream
Range range = doc.getRange();
range.replaceText("my&&nazwa&&firmy", "KAKAOWY SZATAN");
//konwersja na pdf
FileOutputStream fos = new FileOutputStream(pathToDirectory + File.separator + folderName+File.separator + "wniosekzaciagniecie.docx");
doc.write(fos);
String inputChangeFile = pathToDirectory+ File.separator +folderName+File.separator+"wniosekzaciagniecie.docx";
InputStream inputstream = new FileInputStream(inputFilename);
length = inputChangeFile.length();
System.out.println("dlugosc lancucha " + length);
XWPFDocument document = new XWPFDocument(inputstream);
System.out.println("message3");
PdfOptions options = PdfOptions.create();
PdfOptions options = PdfOptions.create().fontEncoding("windows-1250");
System.out.println("message4");
OutputStream out = new FileOutputStream(new File(pathToDirectory+ File.separator +folderName+File.separator+"kakaowyszal.pdf"));
PdfConverter.getInstance().convert(document, out, options);
System.out.println("message5");
}
}
catch( Exception ex){
System.out.println("err" + ex);
return -1;
}

Related

ExceptionInInitializerError on Itext 7

I tried to make PDF with itext 7.2.1, this is my code:
try{
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Kegiatan/" + eventName + ".pdf";
File file = new File(path);
file.mkdirs();
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document document = new Document(pdfDoc, new PageSize(612, 936).rotate());
document.setMargins(0,0,0,0);
//Title
Paragraph paragraph = new Paragraph();
paragraph.add(new Text(eventName).setFontSize(14).setTextAlignment(TextAlignment.CENTER).setBold());
document.add(paragraph);
document.close();
}
catch (IOException e) {
e.printStackTrace();
}
I got this error message, pointing at document.close()
java.lang.ExceptionInInitializerError
How i can fix this?

Send DataSet data email via attachment Excel File xls ( Not Creating Excel File ) C#

I want to send DataSet data with email excel file attachment in C# but I don't want to create Excel file physically. It can be do with MemoryStream but I couldn't.
Another problem I want to set Excel file's encoding type because data may be Russian or Turkish special character.
Please help me...
Here is my sample code...
<!-- language: c# -->
var response = HttpContext.Response;
response.Clear();
response.Charset = "utf-8";
response.ContentEncoding = System.Text.Encoding.Default;
GridView excelGridView = new GridView();
excelGridView.DataSource = InfoDataSet;
excelGridView.DataBind();
excelStringWriter = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(excelStringWriter);
excelGridView.RenderControl(htw);
byte[] ExcelData = emailEncoding.GetBytes(excelStringWriter.ToString());
MemoryStream ms = new MemoryStream(ExcelData);
mailMessage.Attachments.Add(new Attachment(ms, excelFileName, "application/ms-excel"));
<!-- language: c# -->
here is another one simple and easy with excel attchment
public string SendMail(string LastId)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
SqlCommand cmd = new SqlCommand("sp_GetMailData", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#LastID", LastId);
con.Open();
string result = "0";
string temptext = "";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
//ExportToSpreadsheet(dt,"My sheet");
GridView gv = new GridView();
gv.DataSource = dt;
gv.DataBind();
AttachandSend(gv);
con.Close();
return result.ToString();
}
public void AttachandSend(GridView gv)
{
StringWriter stw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(stw);
gv.RenderControl(hw);
System.Text.Encoding Enc = System.Text.Encoding.ASCII;
byte[] mBArray = Enc.GetBytes(stw.ToString());
System.IO.MemoryStream mAtt = new System.IO.MemoryStream(mBArray, false);
System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
MailAddress address = new
MailAddress("xxxxxxxxxxxxx", "Admin");
mailMessage.Attachments.Add(new Attachment(mAtt, "sales.xls"));
mailMessage.Body = "Hi PFA";
mailMessage.From = address;
mailMessage.To.Add("xxxxxxxxxxxx");
mailMessage.Subject = "xxxxxxxxxxxxxx";
mailMessage.IsBodyHtml = true;
var smtp = new SmtpClient();
smtp.Send(mailMessage);
}
Here is your solution
private static Stream DataTableToStream(DataTable table)
{
const string semiColon = ";";
var ms = new MemoryStream();
var sw = new StreamWriter(ms);
foreach (DataColumn column in table.Columns)
{
sw.Write(column.ColumnName);
sw.Write(semiColon);
}
sw.Write(Environment.NewLine);
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
sw.Write(row[i].ToString().Replace(semiColon, string.Empty));
sw.Write(semiColon);
}
sw.Write(Environment.NewLine);
}
return ms;
}
private static MailMessage CreateMail(string from,
string to,
string subject,
string body,
string attname,
Stream tableStream)
{
// using System.Net.Mail
var mailMsg = new MailMessage(from, to, subject, body);
tableStream.Position = 0;
mailMsg.Attachments.Add(
new Attachment(tableStream, attname, CsvContentType));
return mailMsg;
}
private const string CsvContentType = "application/ms-excel";
private static void ExportToSpreadsheetInternal(Stream tableStream, string name)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
context.Response.ContentType = CsvContentType;
context.Response.AppendHeader(
"Content-Disposition"
, "attachment; filename=" + name + ".xls");
tableStream.Position = 0;
tableStream.CopyTo(context.Response.OutputStream);
context.Response.End();
}
public static void ExportToSpreadsheet(DataTable table, string name)
{
var stream = DataTableToStream(table);
var mailMsg = CreateMail("from#ddd.com",
"to#ddd.com",
"spread",
"the spread",
name,
stream);
//ExportToSpreadsheetInternal(stream, name);
// send the mailMsg with SmtpClient (config in your web.config)
var smtp = new SmtpClient();
smtp.Send(mailMsg);
}
Call this method
ExportToSpreadsheet(DataTable table, string name)

POI not sending xls file as attachment , sending as string

one of my junior code is not sending excel file as attachment . It is sending file like
------=_Part_0_2066339629.1374147892060
Content-Type: text/plain; name="Service_Change_Alert_Thu Jul 18 17:14:50 IST 2013.xlsx"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="Service_Change_Alert_Thu Jul 18 17:14:50 IST 2013.xlsx"
UEsDBBQACAAIANqJ8kIAAAAAAAAAAAAAAAARAAAAZG9jUHJvcHMvY29yZS54bWytkV1LwzAUhu/7
K0Lu2yTr1BHaDlEGguLADsW7kB7bYvNBEu3892bdrCheennyPu/D4aRY79WA3sH53ugSs4xiBFqa
ptdtiXf1Jl3hdZUkhTQOts5YcKEHj2JL+xJ3IVhOiJcdKOGzGOuYvBinRIija4kV8lW0QBaUnhMF
QTQiCHKwpXbW4aOPS/vvykbOSvvmhknQSAIDKNDBE5Yx8s0GcMr/WZiSmdz7fqbGcczGfOLiRow8
3d0+TMunvfZBaAm4ShAqTnYuHYgADYoOHj4slPgrecyvrusNrhaU5Sm9SNmqZowvl/yMPhfkV//k
function is following
public void sendSeviceabilityMail(List<OctpinSaveBean> datalist)
throws MessagingException {
Session session = null;
Map<String, String> utilsMap = ApplicationBean.utilsProperties;
if (utilsMap == null || utilsMap.size() == 0)
utilsMap = ApplicationBean.getUtilsPropertyFileValues();
smtpHost = utilsMap.get("SMTPHost");
to = utilsMap.get("To");
try {
if (smtpHost != null && to != null) {
Date date = new Date();
XSSFWorkbook updateDataBook =
updatedServiceabilityExcel(datalist);
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpHost);
props.put("To", to);
session = Session.getInstance(props, null);
String str = "strstr";
Multipart multipart = new MimeMultipart();
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setContent(str, "text/html");
BodyPart messageBodyPart = new MimeBodyPart();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
updateDataBook.write(baos);
byte[] bytes = baos.toByteArray();
DataSource ds = new ByteArrayDataSource(bytes,
"application/vnd.ms-excel");
DataHandler dh = new DataHandler(ds);
messageBodyPart.setDataHandler(dh);
String fileName = "Service_Change_Alert_" + date+".xlsx";
messageBodyPart.setFileName(fileName);
messageBodyPart.setHeader("Content-disposition", "attachment;
filename=\"" + fileName + "\"");
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart);
if (to != null && to.length() > 0) {
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("tech_noida
<tech_noida#xyz.com>"));
String[] toArray = to.split(",");
InternetAddress[] address = new
InternetAddress[toArray.length];
for (int i = 0; i < toArray.length; i++) {
address[i] = new InternetAddress(toArray[i]);
}
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("Updated Serviceability Alert!!!");
msg.setContent(multipart);
msg.setSentDate(date);
try {
Transport.send(msg);
logger.info("Mail has been sent about the updated serviceability alert to :" + to);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
The problem is not related to POI, but with JavaMail (plus the way different email clients handles the specs and malformed emails). Try this:
Multipart multipart = new MimeMultipart();
MimeBodyPart html = new MimeBodyPart();
// Use actual html not "strstr"
html.setContent("<html><body><h1>Hi</h1></body></html>", "text/html");
multipart.addBodyPart(html);
// ...
// Joop Eggen suggestion to avoid spaces in the file name
String fileName = "Service_Change_Alert_"
+ new SimpleDateFormat("yyyy-MM-dd_HH:mm").format(date) + ".xlsx";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
updateDataBook.write(baos);
byte[] poiBytes = baos.toByteArray();
// Can be followed by the DataSource / DataHandler stuff if you really need it
MimeBodyPart attachment = new MimeBodyPart();
attachment.setFileName(filename);
attachment.setContent(poiBytes, "application/vnd.ms-excel");
//attachment.setDataHandler(dh);
attachment.setDisposition(MimeBodyPart.ATTACHMENT);
multipart.addBodyPart(attachment);
Update:
Also don't forget to call saveChanges to update the headers before sending the message.
msg.saveChanges();
See this answer for further details.

How to add download option for openwith and saveAs on exporting file to excel in servlet

Hii Guys !!!
I made an application in which i need to export data from database into .excel formate in which i have given hard coded path for generated .excel file to save at particular position on the system.Now as per my requirement I need to give download option for openwith and saveAs from the browser.
Below I am postion my code .Plz guys help me ...will be gratefull.Thanx in advance...
String datum1 = request.getParameter("fromdate");
String datum2 = request.getParameter("todate");
SimpleDateFormat sdfSource = new SimpleDateFormat("dd-MM-yyyy");
Date date = sdfSource.parse(datum1);
Date date2 = sdfSource.parse(datum2);
SimpleDateFormat sdfDestination = new SimpleDateFormat("yyyy-MM-dd");
datum1 = sdfDestination.format(date);
System.out.println(datum1);
datum2 = sdfDestination.format(date2);
System.out.println(datum2);
String filename = "d:/".concat(datum1).concat(" ").concat("To").concat(" ").concat(datum2).concat(".xls");
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("CallBillingSystem");
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell((short) 0).setCellValue("calldate");
rowhead.createCell((short) 1).setCellValue("src");
rowhead.createCell((short) 2).setCellValue("dst");
String strQuery = "";
ResultSet rs = null;
conexion conexiondb = new conexion();
conexiondb.Conectar();
strQuery = "SELECT * FROM cdrcost where date(calldate) between '" + datum1 + "' and '" + datum2 + "'";
// strQuery = "SELECT * FROM cdrcost where date(calldate) between '2011-09-01' and '2012-01-01'";
rs = conexiondb.Consulta(strQuery);
int i = 1;
while (rs.next()) {
HSSFRow row = sheet.createRow((short) i);
row.createCell((short) 0).setCellValue(rs.getString("calldate"));
row.createCell((short) 1).setCellValue(rs.getString("src"));
row.createCell((short) 2).setCellValue(rs.getString("dst"));
i++;
}
FileOutputStream fileOut = new FileOutputStream(filename);
hwb.write(fileOut);
fileOut.close();
System.out.println("Your excel file has been generated!");
} catch (Exception ex) {
System.out.println(ex);
}
}
You should use Content-Disposition in the response header
Try using this code
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=FileName.xls");
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(my_file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.flush();

Export xml data to Excel using OpenXML

The file is downloading an xlsx file but when i tried to open the file it is saying file is corrupted. Here is the code i'm trying to use please let me know if any changes has to be done for the following.
private void button1_Click(object sender, EventArgs e)
{
ArrayList DataNode = new ArrayList();
XmlDocument xmlobj = new XmlDocument();
ArrayList FinalXML = new ArrayList();
XslCompiledTransform xXslt = new XslCompiledTransform();
xmlobj.Load(#"D:\ExcelImport\Input.xml");
xXslt.Load(#"D:\ExcelImport\demoxsl.xslt");
XmlNodeList DN ;
DN = xmlobj.DocumentElement.GetElementsByTagName("Data");
for (int i = 0; i < DN.Count; i++)
{
DataNode.Add("<ShaleDataExport><Data Flag = '" + i + "' >" + DN.Item(i).InnerXml + "</Data></ShaleDataExport>");
}
string ShaleDataExportXML;
int k = 0 ;
while (k < DN.Count)
{
ShaleDataExportXML = DataNode[k].ToString();
XmlDocument xml = new XmlDocument();
xml.LoadXml(ShaleDataExportXML);
StringWriter sw = new StringWriter();
xXslt.Transform(xml, null, sw);
FinalXML.Add(sw);
sw.Close();
k++;
}
using (SpreadsheetDocument doc = SpreadsheetDocument.Create(#"D:\ExcelImport\OutPut\OutPut.xlsx", DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbook = doc.AddWorkbookPart();
string XML;
string WorbookXML;
WorbookXML = #"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><workbook xmlns=""schemas.openxmlformats.org/.../main"" xmlns:r=""schemas.openxmlformats.org/.../relationships""><sheets>";
for (int j = 0; j < DN.Count; j++)
{
WorksheetPart[] sheet = new WorksheetPart[DN.Count];
sheet[j] = workbook.AddNewPart<WorksheetPart>();
string sheetId = workbook.GetIdOfPart(sheet[j]);
XML = #"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><worksheet xmlns=""schemas.openxmlformats.org/.../main"" >";
XML += FinalXML[j].ToString() + "</worksheet>";
string SheetXML = XML.ToString();
XmlDocument SXML = new XmlDocument();
SXML.LoadXml(SheetXML);
byte[] byteArray = Encoding.ASCII.GetBytes(SXML.OuterXml);
MemoryStream stream = new MemoryStream(byteArray);
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
WorbookXML += "<sheet name="+ AddPartXml(sheet[j], text) + " sheetId=" + j.ToString() + " r:id=" + sheetId.ToString() + " />";
}
WorbookXML += "</sheets></workbook>";
AddPartXml(workbook, WorbookXML);
doc.Close();
}
}
public string AddPartXml(OpenXmlPart part, string xml)
{
Uri uri = part.Uri;
String[] sheetNames = uri.OriginalString.Split('/');
string sheetName = sheetNames[sheetNames.Length - 1].Split('.')[0];
using (Stream stream = part.GetStream())
{
byte[] buffer = (new UTF8Encoding()).GetBytes(xml);
stream.Write(buffer, 0, buffer.Length);
}
return sheetName;
}
Thanks in advance
Vineet Mangal
private void button1_Click(object sender, EventArgs e)
{
XmlDocument xmlobj = new XmlDocument();
xmlobj.Load(#"C:\Excel Import\\Input.xml");
XslCompiledTransform xXslt = new XslCompiledTransform();
xXslt.Load(#"C:\ExportToexcel\Data.xslt");
StringWriter sw = new StringWriter();
xXslt.Transform(xmlobj, null, sw);
richTextBox2.Text = sw.ToString();
sw.Close();
XmlDocument Xdoc = new XmlDocument();
Xdoc.LoadXml(sw.ToString());
Xdoc.Save(#"c:\temp\output.xml");
StreamReader sr = File.OpenText(#"c:\temp\output.xml");
string strSheetData = sr.ReadToEnd();
ArrayList DataNode = new ArrayList();
ArrayList FinalXML = new ArrayList();
XmlNodeList DN;
DN = xmlobj.DocumentElement.GetElementsByTagName("Data");
for (int i = 0; i < DN.Count; i++)
{
DataNode.Add("<ShaleDataExport><Data Flag = '" + i + "' >" + DN.Item(i).InnerXml + "</Data></ShaleDataExport>");
}
string ShaleDataExportXML;
int k = 0;
while (k < DN.Count)
{
ShaleDataExportXML = DataNode[k].ToString();
XmlDocument xml = new XmlDocument();
xml.LoadXml(ShaleDataExportXML);
StringWriter sw1 = new StringWriter();
xXslt.Transform(xml, null, sw1);
FinalXML.Add(sw1);
sw.Close();
k++;
}
using (SpreadsheetDocument doc = SpreadsheetDocument.Create(#"c:\\temp\\output.xlsx", DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbook1 = doc.AddWorkbookPart();
string XML;
string WorbookXML;
WorbookXML = #"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><workbook xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships""><sheets>";
for (int j = 0; j < DN.Count; j++)
{
WorksheetPart[] sheet = new WorksheetPart[DN.Count];
sheet[j] = workbook1.AddNewPart<WorksheetPart>();
string sheetId = workbook1.GetIdOfPart(sheet[j]);
XML = #"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><worksheet xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" >";
XML += FinalXML[j].ToString() + "</worksheet>";
string SheetXML = XML.ToString();
XmlDocument SXML = new XmlDocument();
SXML.LoadXml(SheetXML);
byte[] byteArray = Encoding.ASCII.GetBytes(SXML.OuterXml);
MemoryStream stream = new MemoryStream(byteArray);
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
**WorbookXML += "<sheet name=" + "\"sheet" + (j + 1).ToString() + "\" " + " sheetId=\"" + (j + 1).ToString() + "\" r:id=\"" + sheetId.ToString() + "\" />";
AddPartXml(sheet[j], text);**
}
WorbookXML += "</sheets></workbook>";
AddPartXml(workbook1, WorbookXML);
doc.Close();
}
}
public void AddPartXml(OpenXmlPart part, string xml)
{
**using (Stream stream = part.GetStream())
{
byte[] buffer = (new UTF8Encoding()).GetBytes(xml);
stream.Write(buffer, 0, buffer.Length);
}**
}

Resources