How to append data in excel with another worksheet - c#

I have created an existing excel with two worksheet. For my first worksheet it consist of data and I would like to add another data into same excel but second worksheet. Can I know why my code doesn't work?
public byte[] ExportToExcel()
{
Warning[] warnings = null;
string[] streamids = null;
string mimeType = null;
string encoding = null;
string extension = null;
byte[] content;
content = this.ReportViewer.LocalReport.Render("Excel", null, out mimeType, out encoding, out extension, out streamids, out warnings);
return content;
}
ReportContent = ExportToExcel();
var path = ScheduledService.gstrReportPath;
var fullpath = Path.Combine(path, "ServerReport" + "_" + "_" + DateTime.Now.ToString("yyMMdd") + ".xls");
bool exists = System.IO.Directory.Exists(path);
if (!exists)
System.IO.Directory.CreateDirectory(path);
//Problem --------------------------------------------------------------------
FileStream file = File.Open(fullpath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite);
file.Write(ReportContent, 0, ReportContent.Length);
file.Flush();
file.Close();

Perhaps this post helps. I found similar comments on StackOverflow too. Set a property PageBreakAtEnd = true on appropriate object such as a rectangle or tablix. This will create a new Worksheet.

Related

How to save a report directly to .doc?

I have a report and i want to save it directly without a dialog.
Here is my code until now
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.InitialDirectory = #"C:\temp";
saveFileDialog.RestoreDirectory = true;
saveFileDialog.Title = "Browse Text Files";
saveFileDialog.DefaultExt = "doc";
saveFileDialog.Filter = "Word Doc (*.doc)|*.doc|PDF (*.pdf)| *.pdf";
saveFileDialog.CheckFileExists = false;
saveFileDialog.CheckPathExists = true;
Warning[] warnings;
string[] streams;
string mimeType;
string encoding;
string extension;
byte[] bytes = reportTest.LocalReport.Render("Word", null, out mimeType, out encoding, out extension, out streams, out warnings);
//if (saveFileDialog.ShowDialog() == DialogResult.OK)
//{
saveFileDialog.FileName = "123.doc";
var filename = saveFileDialog.FileName;
System.IO.FileStream file = new FileStream(filename, FileMode.Create);
file.Write(bytes, 0, bytes.Length);
file.Close();
//}
Can someone help me how to save the file directly to c:\temp\123.doc (without dialog in the explorer).
Thanks a lot!
You can directly save this with path and file name
filename="PATH" + "test.doc";
System.IO.FileStream file = new FileStream(filename, FileMode.Create);

View RDLC Report as pdf in Asp.net MVC

I am facing problem in last two days. I am trying to view rdlc report as pdf without reportviewer. I export rdlc to pdf using the following code...
public string Export(LocalReport rpt, string filePath)
{
string ack = "";
try
{
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string extension;
byte[] bytes = rpt.Render("PDF", null, out mimeType, out encoding, out extension, out streamids, out warnings);
using (FileStream stream = File.OpenWrite(filePath))
{
stream.Write(bytes, 0, bytes.Length);
}
return ack;
}
catch(Exception ex)
{
ack = ex.InnerException.Message;
return ack;
}
}
The pdf file exported to User->AppData->Temp
string filePath = System.IO.Path.GetTempFileName();
string ack = Export(rpt, Server.MapPath("~/Reports/Mymun_Lab/ComparisonStudy.rdlc"));
System.Diagnostics.Process.Start(filePath);
I want to render this pdf file to the client PC.
This Code is work fine on my local machine. But when i publish this to IIS Server and run for try to get the exported pdf file to client PC not success. How can i solve this issue. Can anyone help me.
Thanks In Advance...
Finally, i found one solution about view RDLC report as pdf in asp.net MVC. The solution is following....
public FileResult ViewReport()
{
string RptPath = Server.MapPath("~/Reports/Mymun_Lab/ComparisonStudy.rdlc");
Microsoft.Reporting.WebForms.LocalReport rpt = new Microsoft.Reporting.WebForms.LocalReport();
/* Bind Here Report Data Set */
rpt.ReportPath = RptPath;
string filePath = System.IO.Path.GetTempFileName();
Export(rpt, filePath);
//CLOSE REPORT OBJECT
rpt.Dispose();
return File(filePath, "application/pdf");
}
I use the following method for generate pdf from RDLC....
public string Export(LocalReport rpt, string filePath)
{
string ack = "";
try
{
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string extension;
byte[] bytes = rpt.Render("PDF", null, out mimeType, out encoding, out extension, out streamids, out warnings);
using (FileStream stream = File.OpenWrite(filePath))
{
stream.Write(bytes, 0, bytes.Length);
}
return ack;
}
catch(Exception ex)
{
ack = ex.InnerException.Message;
return ack;
}
}
[HttpPost]
public async Task<FileResult> DownloadReport(string id, string firstName, string lastName)
{
var result = await accountRepository.GetUserLogInDetailsByID(id);
//string RptPath = Server.MapPath("~/RDLC/rptUserLogInDetails.rdlc");
string RptPath = Server.MapPath("~/RDLC/rptUserLogInDetails.rdlc");
ReportViewer rv = new ReportViewer();
ReportDataSource rds = new ReportDataSource();
rds.Name = "DataSet1";
rds.Value = result;
string companyName = WebConfigurationManager.AppSettings["CompanyName"];
ReportParameter[] parameters = new ReportParameter[2];
parameters[0] = new ReportParameter("username", firstName + " " + lastName);
parameters[1] = new ReportParameter("companyName", companyName);
//ReportViewer rv = new Microsoft.Reporting.WebForms.ReportViewer();
rv.ProcessingMode = ProcessingMode.Local;
rv.LocalReport.ReportPath = RptPath;
// Add the new report datasource to the report.
rv.LocalReport.DataSources.Add(rds);
rv.LocalReport.EnableHyperlinks = true;
rv.LocalReport.SetParameters(parameters);
rv.LocalReport.Refresh();
byte[] streamBytes = null;
string mimeType = "";
string encoding = "";
string filenameExtension = "";
string[] streamids = null;
Warning[] warnings = null;
streamBytes = rv.LocalReport.Render("PDF", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings);
string fileName = "LogInDetails-" + firstName + lastName + ".pdf";
// This will download the pdf file
//return File(streamBytes, mimeType, fileName);
//This will open directly the pdf file
return File(streamBytes, "application/pdf");
}

Extract Visio diagram from word document using open xml?

I am trying to parse the word document, It has visio diagram and images. I am not able to extract diagram and save it in visio format (.vsd, .vdx, .vsdx, .vsdm) Using C# Open XML.
I have found and answer to my own question. below is the code if any one its..
Below code will help you get all the image in word document.
foreach (ImagePart imagePart in doc.MainDocumentPart.ImageParts)
{
var uri = imagePart.Uri;
var IdR = doc.MainDocumentPart.GetIdOfPart(imagePart);
string FileExtension = uri.OriginalString.Split('.').Last();
var filename = uri.ToString().Split('/').Last();
stream = doc.Package.GetPart(uri).GetStream();
Bitmap b = new Bitmap(stream);
string FilePath = #"C:\test"." + FileExtension;
b.Save(FilePath);
}
Below will help you get the embedded object in word document like: Visio, MP3 video.
var IdR = doc.MainDocumentPart.GetIdOfPart(embeddedobjectpart);
string FileExtension = embeddedobjectpart.Uri.OriginalString.Split('.').Last();
FileExtension = "vsd";
stream = doc.Package.GetPart(embeddedobjectpart.Uri).GetStream();
long length = stream.Length;
byte[] byteStream = new byte[length];
stream.Read(byteStream, 0, (int)length);
string FilePath =#"C:\test"." + "." + FileExtension;
fstream = new FileStream(FilePath, FileMode.OpenOrCreate)
fstream.Write(byteStream, 0, (int)length);
fstream.Close();

Report Viewer export to pdf getting error

I am getting this error "Cannot create a data reader for dataset 'DataSet1'."
I expend lots of my time for solving this issue but unable to
resolved.Same code is working good for report generation but at the time of pdf generation it stuck.
Here is my code please reply.
protected void btnPdf_Click(object sender, EventArgs e)
{
string PDF = "PDF";
string ReportType = "ReportType";
Warning[] warnings = null;
string[] streamIds = null;
string mimeType = string.Empty;
string encoding = string.Empty;
string extension = string.Empty;
string filetype = string.Empty;
long _landIds = 0;
if (_farmId > 0)
{
Land land = LandManager.GetLandByFarmID(_farmId);
_landIds = land.LandID;
}
ReportViewer_MyReportID.SizeToReportContent = true;
ReportViewer_MyReportID.LocalReport.ReportPath = "reports/report/report.rdlc";
ReportViewer_MyReportID.ProcessingMode = ProcessingMode.Remote;
ObjectDataSource_Id.SelectParameters.Clear();
ObjectDataSource_Id.SelectParameters.Add(QueryStringEnum.CompanyID, CurrentCompanyID.ToString());
ObjectDataSource_Id.SelectParameters.Add(QueryStringEnum.LandID, _landIds.ToString());
var days = "-" + rdDuration.SelectedValue;
ObjectDataSource_Id.SelectParameters.Add(QueryStringEnum.Days, days.ToString());
ReportViewer_MyReportID.LocalReport.Refresh();
byte[] bytes = ReportViewer_MyReportID.LocalReport.Render("PDF", null,
out mimeType, out encoding, out extension, out streamIds, out warnings);
FileStream fs = new FileStream(Server.MapPath("~/GeneratedFiles/" + ReportType + "." + "PDF"), FileMode.OpenOrCreate);
fs.Write(bytes, 0, bytes.Length);
fs.Close();
}
It will work for you.Make sure dataset name is not different.
Code for your reference.
protected void btnPdf_Click(object sender, EventArgs e)
{
ReportViewer viwer = new ReportViewer();
ObjectDataSource ob = new ObjectDataSource("dataset.YourTableAdapter", "GetData");
dataset.YourTableAdapter ds = new dataset.YourTableAdapter();
string PDF = "PDF";
string ReportType = "ReportType";
Warning[] warnings = null;
string[] streamIds = null;
string mimeType = string.Empty;
string encoding = string.Empty;
string extension = string.Empty;
string filetype = string.Empty;
long _landIds = 0;
if (_farmId > 0)
{
Land land = LandManager.GetLandByFarmID(_farmId);
_landIds = land.LandID;
}
viwer.SizeToReportContent = true;
viwer.LocalReport.ReportPath = "reports/report/report.rdlc";
viwer.ProcessingMode = ProcessingMode.Local;
ob.SelectParameters.Clear();
ob.SelectParameters.Add(QueryStringEnum.CompanyID, CurrentCompanyID.ToString());
ob.SelectParameters.Add(QueryStringEnum.LandID, _landIds.ToString());
var days = "-" + rdDuration.SelectedValue;
ob.SelectParameters.Add(QueryStringEnum.Days, days.ToString());
ReportDataSource rds = new ReportDataSource("datasetname", (object) ds.GetData((long?)CurrentCompanyID.ToInt64(), (int?)days.ToInt(), (long?)_landIds.ToInt64()));
viwer.LocalReport.DataSources.Add(rds);
viwer.LocalReport.Refresh();
byte[] bytes = viwer.LocalReport.Render("PDF", null,
out mimeType, out encoding, out extension, out streamIds, out warnings);
FileStream fs = new FileStream(Server.MapPath("~/GeneratedFiles/" + ReportType + "." + "PDF"), FileMode.OpenOrCreate);
fs.Write(bytes, 0, bytes.Length);
fs.Close();
}

How to upload a file and save it in an specific folder in local computer?

I want to take (upload) a file to a specific folder that I have created in my project (on local computer not a server!).
Here is the code that I am using:
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(Server.MapPath("images/" + filename));
I have added the Fileupload, and the code above in a button. But the code won't work. What's the problem?
I also used this form:
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(Server.MapPath("~DesktopModules/UshtrimiDyte/images/" + filename));
I also used it with double back slashes, but that didn't work either. How can I solve my problem?
Try the above
string path = Server.MapPath("~DesktopModules/UshtrimiDyte/images/" + filename);
System.IO.Stream myStream;
Int32 fileLen;
byte[] Input = null;
fileLen = FileUpload1.PostedFile.ContentLength;
if (fileLen > 0)
{
Input = new Byte[fileLen];
myStream = FileUpload1.FileContent;
myStream.Read(Input, 0, fileLen);
string I_Docx_type = FileUploadFieldDoc.FileName.Substring(FileUpload1.FileName.LastIndexOf(".") + 1);
WriteToFile(path + "." +I_Docx_type, ref Input);
path += "." + I_Docx_type;
}
method
private void WriteToFile(string strPath, ref byte[] Buffer)
{
// Create a file
System.IO.FileStream newFile = new System.IO.FileStream(strPath, System.IO.FileMode.Create);
// Write data to the file
newFile.Write(Buffer, 0, Buffer.Length);
// Close file
newFile.Close();
}

Categories

Resources