Export DataGridView to Excel File - c#

Can you say me, how can i save the contents of DataGridView to Exel File with the Formatting cells Backcolor/Forecolor? I have DGV like this:
And when I try to Export Data to Excel I get the data, but without Forecolor, I have tried a several of ways, but it does not work! Beforehand Thank you!
private void btnExport_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel Documents (*.xls)|*.xls";
sfd.FileName = "export.xls";
if (sfd.ShowDialog() == DialogResult.OK)
{
//ToCsV(dataGridView1, #"c:\export.xls");
ToCsV1(dataGridView1, sfd.FileName);
}
}
private void ToCsV1(DataGridView dGV, string filename)
{
string stOutput = "";
// Export titles:
string sHeaders = "";
for (int j = 0; j < dGV.Columns.Count; j++)
sHeaders = sHeaders.ToString() + Convert.ToString(dGV.Columns[j].HeaderText) + "\t";
stOutput += sHeaders + "\r\n";
// Export data.
for (int i = 0; i < dGV.RowCount - 1; i++)
{
string stLine = "";
for (int j = 0; j < dGV.Rows[i].Cells.Count; j++)
stLine = stLine.ToString() + Convert.ToString(dGV.Rows[i].Cells[j].Value) + "\t";
stOutput += stLine + "\r\n";
}
Encoding utf16 = Encoding.GetEncoding(1254);
byte[] output = utf16.GetBytes(stOutput);
FileStream fs = new FileStream(filename, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(output, 0, output.Length); //write the encoded file
bw.Flush();
bw.Close();
fs.Close();
}

try to export to ExcelXML
Example:
using (var writer = new StreamWriter(fileDialog.OpenFile(), Encoding.UTF8))
{
if (format == "XML")
{
writer.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
writer.WriteLine("<?mso-application progid=\"Excel.Sheet\"?>");
writer.WriteLine("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\">");
writer.WriteLine("<DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">");
writer.WriteLine("<Author></Author>");
writer.WriteLine("<Created>" + DateTime.Now.ToLocalTime().ToLongDateString() + "</Created>");
writer.WriteLine("<LastSaved>" + DateTime.Now.ToLocalTime().ToLongDateString() + "</LastSaved>");
writer.WriteLine("<Company></Company>");
writer.WriteLine("<Version>12.00</Version>");
writer.WriteLine("</DocumentProperties>");
if (showGroupHeaders)
AddStyles(writer, groupDesc.Count());
writer.WriteLine(
"<Worksheet ss:Name=\"Silverlight Export\" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\">");
writer.WriteLine("<Table>");
}
writer.Write(text.ToString());
if (format == "XML")
{
writer.WriteLine("</Table>");
writer.WriteLine("</Worksheet>");
writer.WriteLine("</Workbook>");
}
writer.Close();
}
Where AddStyle Like this:
private static void AddStyles(StreamWriter writer, int groupCount)
{
writer.WriteLine("<Styles>");
for (int i = 0; i < groupCount; i++)
{
int shift = i % _headerColor.Count();
var color = _headerColor[shift];
writer.WriteLine("<Style ss:ID=\"st{0}\">", i + 1);
writer.WriteLine("<Interior ss:Color=\"#{0:X2}{1:X2}{2:X2}\" ss:Pattern=\"Solid\"/>", color.R, color.G, color.B);
writer.WriteLine("</Style>");
}
writer.WriteLine("</Styles>");
}
And Set cell backcolor:
string.Format("<Cell ss:StyleID=\"st{0}\"><Data ss:Type=\"String\">{1}</Data></Cell>", style, data);

Here is an example using GemBox.Spreadsheet component to work with Excel files and cell formatting.

Related

Passing the length and the value on a string format

I have the below code that i m reading from datagrid and i export to ascii file and work fine
FileInfo info = new FileInfo(#"C:\SqlExports\");
info.Directory.Create();
string fileName = condition + " " + date + ".txt";
FileStream stream = new FileStream(#"C:\SqlExports\" + fileName, FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(stream, Encoding.Default);
for (int i = 0; i < Grid.Rows.Count; i++)
{
List<string> rowprint = new List<string>();
for (int f = 0; f < Grid.Columns.Count; f++)
{
if (Grid.Rows[i].Cells[f].Value != DBNull.Value)
{ rowprint.Add(Grid.Rows[i].Cells[f].Value.ToString()); }
else
{
rowprint.Add(" ");
}
}
sw.Write(string.Format("{0,-19}", rowprint[0]) + String.Format("{0,10}", rowprint[1]) + sw.NewLine, Encoding.Default);
}
sw.Close();
I need to make my code reusable so if the grid populated with other datas to read each time what i need.
i tried
sw.Write(string.Format("0, -(rowprint[0].length + 2)", rowprint[0]) + string.Format("{"0,rowprint[1].Length + 2"} + sw.Newlinn, Encoding.Default);
but of course not working so how can i have the length plus 2 blanks and the value?
of course i know that i need a var with the columns because its time maybe the columns is 2 or 3 or etc.

Export DataTable to Excel and save to local directory

I have below functions that take Data Table and convert to excel and prompt user to download the excel.
May I know how can I change the function so that it is save to my local directory instead of download?
public static void ExportDataTableToExcel(DataTable table, string name)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
string attachment = "attachment; filename=" + name + ".xls";
context.Response.ClearContent();
context.Response.AddHeader("content-disposition", attachment);
context.Response.ContentType = "application/vnd.ms-excel";
context.Response.ContentEncoding = System.Text.Encoding.Unicode;
context.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
string tab = "";
foreach (DataColumn dc in table.Columns)
{
context.Response.Write(tab + dc.ColumnName);
tab = "\t";
}
context.Response.Write("\n");
int i;
foreach (DataRow dr in table.Rows)
{
tab = "";
for (i = 0; i < table.Columns.Count; i++)
{
context.Response.Write(tab + "=\"" + dr[i].ToString() + "\"");
tab = "\t";
}
context.Response.Write("\n");
}
context.Response.End();
}
Found and implemented the function
public static bool SaveDataTableToExcel(DataTable table, string savePath)
{
//open file
StreamWriter wr = new StreamWriter(savePath, false, Encoding.Unicode);
try
{
for (int i = 0; i < table.Columns.Count; i++)
{
wr.Write(table.Columns[i].ToString().ToUpper() + "\t");
}
wr.WriteLine();
//write rows to excel file
for (int i = 0; i < (table.Rows.Count); i++)
{
for (int j = 0; j < table.Columns.Count; j++)
{
if (table.Rows[i][j] != null)
{
wr.Write("=\"" + Convert.ToString(table.Rows[i][j]) + "\"" + "\t");
}
else
{
wr.Write("\t");
}
}
//go to next line
wr.WriteLine();
}
//close file
wr.Close();
}
catch (Exception ex)
{
LogError(ex);
return false;
}
return true;
}

Export data to csv file set values to not right cells

I use next code to export data from datagridView into xls file.
private void ToCsV(DataGridView dGv, string filename)
{
var stOutput = "";
// Export titles:
var sHeaders = "";
for (var j = 0; j < dGv.Columns.Count; j++)
sHeaders = sHeaders + Convert.ToString(dGv.Columns[j].HeaderText) + "\t";
stOutput += sHeaders + "\r\n";
// Export data.
for (var i = 0; i < dGv.RowCount - 1; i++)
{
var stLine = "";
for (var j = 0; j < dGv.Rows[i].Cells.Count; j++)
stLine = stLine + Convert.ToString(dGv.Rows[i].Cells[j].Value) + "\t";
stOutput += stLine + "\r\n";
}
var utf16 = Encoding.GetEncoding(1254);
byte[] output = utf16.GetBytes(stOutput);
var fs = new FileStream(filename, FileMode.Create);
var bw = new BinaryWriter(fs);
bw.Write(output, 0, output.Length); //write the encoded file
bw.Flush();
bw.Close();
fs.Close();
}
As result i get "bad" formated file :
I don't know why file content is like this (some text aren't in right columns). Any suggestion? Thanks.
Is it possible because some text for cell has "newLine" \n ?
Enclose all your values (or at least the ones being a potential issue) with double quotes. Instead of 123\n put "123\n" in your csv file.
This issue is most of the time encountered when using decimal separator in csv files, like explained here. Your \n case looks a lot alike.

Datatable to csv write to zip download error: because it is being used by another process

In thst code i have us two database tabele and fetch data in datatable then write all the data in the csv files with help of stream writer then add both the file in a folder and download in a zip form but sometimes its shows an error The process cannot access the file 'xxxxx.zip' because it is being used by another process.
protected void btnExportToCSV_Click(object sender, EventArgs e)
{
//Work Detail
blExportToExcel obj = new blExportToExcel();
System.Data.DataTable dtTechSanc = blDbFunction.GetTechSanc(ddlAgency.SelectedValue.ToString(), ddlDivision.SelectedValue.ToString(), ddlDistrict.SelectedValue.ToString(), ddlMC.SelectedValue.ToString(), ddlScheme.SelectedValue.ToString(), ddlUserType.SelectedValue.ToString(), ddlWorkType.SelectedValue.ToString(), ddlWorkNature.SelectedValue.ToString(), ddlWorkStatus.SelectedValue.ToString(), ((prpSessionData)(Session["sUserInfo"])).UId);
dtTechSanc.Columns["Id"].ColumnName = "WorkCode";
dtTechSanc.Columns["TSId"].ColumnName = "Id";
string filenamezip = "ZipFile\\TechSancRevision_" + DateTime.Now.ToString().Replace(":", "-").Replace("/", "-") + ".zip";
string strPathAndQuery = HttpContext.Current.Request.PhysicalApplicationPath;
string paths = strPathAndQuery + filenamezip;
ZipFile z = ZipFile.Create(paths);
z.BeginUpdate();
if (dtTechSanc.Rows.Count > 0)
{
string tmpPath = Server.MapPath("FileTemplates");
string tmpFileName = "TechSancRevision.csv";
tmpPath = #"" + tmpPath.Replace("/", "\\").Replace("\\Department", "") + "\\" + tmpFileName;
StreamWriter sw = new StreamWriter(tmpPath, false);
int columnCount = dtTechSanc.Columns.Count;
for (int i = 0; i < columnCount; i++)
{
sw.Write(dtTechSanc.Columns[i]);
if (i < columnCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
foreach (DataRow dr in dtTechSanc.Rows)
{
for (int i = 0; i < columnCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < columnCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
z.Add(tmpPath, tmpFileName);
z.CommitUpdate();
}
//Fund Allocation
System.Data.DataTable dtFA = blDbFunction.GetFundAllocationTS(ddlAgency.SelectedValue.ToString(), ddlDivision.SelectedValue.ToString(), ddlDistrict.SelectedValue.ToString(), ddlMC.SelectedValue.ToString(), ddlScheme.SelectedValue.ToString(), ddlUserType.SelectedValue.ToString(), ddlWorkType.SelectedValue.ToString(), ddlWorkNature.SelectedValue.ToString(), ddlWorkStatus.SelectedValue.ToString(), ((prpSessionData)(Session["sUserInfo"])).UId);
if (dtFA.Rows.Count > 0)
{
z.BeginUpdate();
string tmpPath = Server.MapPath("FileTemplates");
string tmpFileName = "FundsAllocationRevision.csv";
tmpPath = #"" + tmpPath.Replace("/", "\\").Replace("\\Department", "") + "\\" + tmpFileName;
dtFA.Columns["FAId"].ColumnName = "Id";
dtFA.Columns["WorkId"].ColumnName = "WorkCode";
StreamWriter sw = new StreamWriter(tmpPath, false);
int columnCount = dtFA.Columns.Count;
for (int i = 0; i < columnCount; i++)
{
sw.Write(dtFA.Columns[i]);
if (i < columnCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
foreach (DataRow dr in dtFA.Rows)
{
for (int i = 0; i < columnCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < columnCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
z.Add(tmpPath, tmpFileName);
z.CommitUpdate();
z.Close();
}
System.IO.FileInfo file = new System.IO.FileInfo(paths);
Response.ContentType = "application/text";
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + Path.GetFileName(paths));
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);/// error shows here
Response.End();
}
}
I am not sure this will help you or not but i am transmitting zip using below code , please try it. It works perfectly and in use from past 2 years.
Response.ContentType = "application/zip";
Response.AppendHeader("Content-Disposition", "attachment; filename=Test.zip")
Response.TransmitFile(#"C:\Test.zip");
Response.Flush();
// Prevents any other content from being sent to the browser
Response.SuppressContent = true;
// Directs the thread to finish, bypassing additional processing
HttpContext.Current.ApplicationInstance.CompleteRequest();

Merging multiple PDFs using iTextSharp in c#.net

Well i'm trying to merge multiple PDFs in to one.
I gives no errors while compiling. I tried to merge the docs first but that went wrong because I'm working with tables.
This is the asp.net code-behind
if (Button.Equals("PreviewWord")) {
String eventTemplate = Server.MapPath("/ERAS/Badges/Template/EventTemp" + EventName + ".doc");
String SinglePreview = Server.MapPath("/ERAS/Badges/Template/PreviewSingle" + EventName + ".doc");
String PDFPreview = Server.MapPath("/ERAS/Badges/Template/PDFPreviewSingle" + EventName + ".pdf");
String previewPDFs = Server.MapPath("/ERAS/Badges/Template/PreviewPDFs" + EventName + ".pdf");
if (System.IO.File.Exists((String)eventTemplate))
{
if (vulGegevensIn == true)
{
//This creates a Worddocument and fills in names etc from database
CreateWordDocument(vulGegevensIn, eventTemplate, SinglePreview, false);
//This saves the SinglePreview.doc as a PDF #param place of PDFPreview
CreatePDF(SinglePreview, PDFPreview);
//Trying to merge
String[] previewsSmall=new String[1];
previewsSmall[0] = PDFPreview;
PDFMergenITextSharp.MergeFiles(previewPDFs, previewsSmall);
}
// merge PDFs here...........................;
//here
//no here//
//...
} }
This is the PDFMergenITextSharpClass
public static class PDFMergenITextSharp
{
public static void MergeFiles(string destinationFile, string[] sourceFiles)
{
try
{
int f = 0;
// we create a reader for a certain document
PdfReader reader = new PdfReader(sourceFiles[f]);
// we retrieve the total number of pages
int n = reader.NumberOfPages;
//Console.WriteLine("There are " + n + " pages in the original file.");
// step 1: creation of a document-object
Document document = new Document(reader.GetPageSizeWithRotation(1));
// step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));
// step 3: we open the document
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
int rotation;
// step 4: we add content
while (f < sourceFiles.Length)
{
int i = 0;
while (i < n)
{
i++;
document.SetPageSize(reader.GetPageSizeWithRotation(i));
document.NewPage();
page = writer.GetImportedPage(reader, i);
rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
//Console.WriteLine("Processed page " + i);
}
f++;
if (f < sourceFiles.Length)
{
reader = new PdfReader(sourceFiles[f]);
// we retrieve the total number of pages
n = reader.NumberOfPages;
//Console.WriteLine("There are " + n + " pages in the original file.");
}
}
// step 5: we close the document
document.Close();
}
catch (Exception e)
{
string strOb = e.Message;
}
}
public static int CountPageNo(string strFileName)
{
// we create a reader for a certain document
PdfReader reader = new PdfReader(strFileName);
// we retrieve the total number of pages
return reader.NumberOfPages;
}
}
I found the answer:
Instead of the 2nd Method, add more files to the first array of input files.
public static void CombineMultiplePDFs(string[] fileNames, string outFile)
{
// step 1: creation of a document-object
Document document = new Document();
//create newFileStream object which will be disposed at the end
using (FileStream newFileStream = new FileStream(outFile, FileMode.Create))
{
// step 2: we create a writer that listens to the document
PdfCopy writer = new PdfCopy(document, newFileStream);
// step 3: we open the document
document.Open();
foreach (string fileName in fileNames)
{
// we create a reader for a certain document
PdfReader reader = new PdfReader(fileName);
reader.ConsolidateNamedDestinations();
// step 4: we add content
for (int i = 1; i <= reader.NumberOfPages; i++)
{
PdfImportedPage page = writer.GetImportedPage(reader, i);
writer.AddPage(page);
}
PRAcroForm form = reader.AcroForm;
if (form != null)
{
writer.CopyAcroForm(reader);
}
reader.Close();
}
// step 5: we close the document and writer
writer.Close();
document.Close();
}//disposes the newFileStream object
}
I found a very nice solution on this site : http://weblogs.sqlteam.com/mladenp/archive/2014/01/10/simple-merging-of-pdf-documents-with-itextsharp-5-4-5.aspx
I update the method in this mode :
public static bool MergePdfs(IEnumerable<string> fileNames, string targetFileName)
{
bool success = true;
using (FileStream stream = new(targetFileName, FileMode.Create))
{
Document document = new();
PdfCopy pdf = new(document, stream);
PdfReader? reader = null;
try
{
document.Open();
foreach (string file in fileNames)
{
reader = new PdfReader(file);
pdf.AddDocument(reader);
reader.Close();
}
}
catch (Exception)
{
success = false;
reader?.Close();
}
finally
{
document?.Close();
}
}
return success;
}
Code For Merging PDF's in Itextsharp
public static void Merge(List<String> InFiles, String OutFile)
{
using (FileStream stream = new FileStream(OutFile, FileMode.Create))
using (Document doc = new Document())
using (PdfCopy pdf = new PdfCopy(doc, stream))
{
doc.Open();
PdfReader reader = null;
PdfImportedPage page = null;
//fixed typo
InFiles.ForEach(file =>
{
reader = new PdfReader(file);
for (int i = 0; i < reader.NumberOfPages; i++)
{
page = pdf.GetImportedPage(reader, i + 1);
pdf.AddPage(page);
}
pdf.FreeReader(reader);
reader.Close();
File.Delete(file);
});
}
}
Using iTextSharp.dll
protected void Page_Load(object sender, EventArgs e)
{
String[] files = #"C:\ENROLLDOCS\A1.pdf,C:\ENROLLDOCS\A2.pdf".Split(',');
MergeFiles(#"C:\ENROLLDOCS\New1.pdf", files);
}
public void MergeFiles(string destinationFile, string[] sourceFiles)
{
if (System.IO.File.Exists(destinationFile))
System.IO.File.Delete(destinationFile);
string[] sSrcFile;
sSrcFile = new string[2];
string[] arr = new string[2];
for (int i = 0; i <= sourceFiles.Length - 1; i++)
{
if (sourceFiles[i] != null)
{
if (sourceFiles[i].Trim() != "")
arr[i] = sourceFiles[i].ToString();
}
}
if (arr != null)
{
sSrcFile = new string[2];
for (int ic = 0; ic <= arr.Length - 1; ic++)
{
sSrcFile[ic] = arr[ic].ToString();
}
}
try
{
int f = 0;
PdfReader reader = new PdfReader(sSrcFile[f]);
int n = reader.NumberOfPages;
Response.Write("There are " + n + " pages in the original file.");
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
int rotation;
while (f < sSrcFile.Length)
{
int i = 0;
while (i < n)
{
i++;
document.SetPageSize(PageSize.A4);
document.NewPage();
page = writer.GetImportedPage(reader, i);
rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
Response.Write("\n Processed page " + i);
}
f++;
if (f < sSrcFile.Length)
{
reader = new PdfReader(sSrcFile[f]);
n = reader.NumberOfPages;
Response.Write("There are " + n + " pages in the original file.");
}
}
Response.Write("Success");
document.Close();
}
catch (Exception e)
{
Response.Write(e.Message);
}
}
Merge byte arrays of multiple PDF files:
public static byte[] MergePDFs(List<byte[]> pdfFiles)
{
if (pdfFiles.Count > 1)
{
PdfReader finalPdf;
Document pdfContainer;
PdfWriter pdfCopy;
MemoryStream msFinalPdf = new MemoryStream();
finalPdf = new PdfReader(pdfFiles[0]);
pdfContainer = new Document();
pdfCopy = new PdfSmartCopy(pdfContainer, msFinalPdf);
pdfContainer.Open();
for (int k = 0; k < pdfFiles.Count; k++)
{
finalPdf = new PdfReader(pdfFiles[k]);
for (int i = 1; i < finalPdf.NumberOfPages + 1; i++)
{
((PdfSmartCopy)pdfCopy).AddPage(pdfCopy.GetImportedPage(finalPdf, i));
}
pdfCopy.FreeReader(finalPdf);
}
finalPdf.Close();
pdfCopy.Close();
pdfContainer.Close();
return msFinalPdf.ToArray();
}
else if (pdfFiles.Count == 1)
{
return pdfFiles[0];
}
return null;
}
I don't see this solution anywhere and supposedly ... according to one person, the proper way to do it is with copyPagesTo(). This does work I tested it. Your mileage may vary between city and open road driving. Goo luck.
public static bool MergePDFs(List<string> lststrInputFiles, string OutputFile, out int iPageCount, out string strError)
{
strError = string.Empty;
PdfWriter pdfWriter = new PdfWriter(OutputFile);
PdfDocument pdfDocumentOut = new PdfDocument(pdfWriter);
PdfReader pdfReader0 = new PdfReader(lststrInputFiles[0]);
PdfDocument pdfDocument0 = new PdfDocument(pdfReader0);
int iFirstPdfPageCount0 = pdfDocument0.GetNumberOfPages();
pdfDocument0.CopyPagesTo(1, iFirstPdfPageCount0, pdfDocumentOut);
iPageCount = pdfDocumentOut.GetNumberOfPages();
for (int ii = 1; ii < lststrInputFiles.Count; ii++)
{
PdfReader pdfReader1 = new PdfReader(lststrInputFiles[ii]);
PdfDocument pdfDocument1 = new PdfDocument(pdfReader1);
int iFirstPdfPageCount1 = pdfDocument1.GetNumberOfPages();
iPageCount += iFirstPdfPageCount1;
pdfDocument1.CopyPagesTo(1, iFirstPdfPageCount1, pdfDocumentOut);
int iFirstPdfPageCount00 = pdfDocumentOut.GetNumberOfPages();
}
pdfDocumentOut.Close();
return true;
}
Please also visit and read this article where I explained everything in detail about How to Merge Multiple PDF Files Into Single PDF Using Itextsharp in C#
Implementation:
try
{
string FPath = "";
// Create For loop for get/create muliple report on single click based on row of gridview control
for (int j = 0; j < Gridview1.Rows.Count; j++)
{
// Return datatable for data
DataTable dtDetail = new My_GlobalClass().GetDataTable(Convert.ToInt32(Gridview1.Rows[0]["JobId"]));
int i = Convert.ToInt32(Gridview1.Rows[0]["JobId"]);
if (dtDetail.Rows.Count > 0)
{
// Create Object of ReportDocument
ReportDocument cryRpt = new ReportDocument();
//Store path of .rpt file
string StrPath = Application.StartupPath + "\\RPT";
StrPath = StrPath + "\\";
StrPath = StrPath + "rptCodingvila_Articles_Report.rpt";
cryRpt.Load(StrPath);
// Assign Report Datasource
cryRpt.SetDataSource(dtDetail);
// Assign Reportsource to Report viewer
CryViewer.ReportSource = cryRpt;
CryViewer.Refresh();
// Store path/name of pdf file one by one
string StrPathN = Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report" + i.ToString() + ".Pdf";
FPath = FPath == "" ? StrPathN : FPath + "," + StrPathN;
// Export Report in PDF
cryRpt.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, StrPathN);
}
}
if (FPath != "")
{
// Check for File Existing or Not
if (System.IO.File.Exists(Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report.pdf"))
System.IO.File.Delete(Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report.pdf");
// Split and store pdf input file
string[] files = FPath.Split(',');
// Marge Multiple PDF File
MargeMultiplePDF(files, Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report.pdf");
// Open Created/Marged PDF Output File
Process.Start(Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report.pdf");
// Check and Delete Input file
foreach (string item in files)
{
if (System.IO.File.Exists(item.ToString()))
System.IO.File.Delete(item.ToString());
}
}
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Create Function for Marge PDF
public static void MargeMultiplePDF(string[] PDFfileNames, string OutputFile)
{
iTextSharp.text.Document PDFdoc = new iTextSharp.text.Document();
using (System.IO.FileStream MyFileStream = new System.IO.FileStream(OutputFile, System.IO.FileMode.Create))
{
iTextSharp.text.pdf.PdfCopy PDFwriter = new iTextSharp.text.pdf.PdfCopy(PDFdoc, MyFileStream);
if (PDFwriter == null)
{
return;
}
PDFdoc.Open();
foreach (string fileName in PDFfileNames)
{
iTextSharp.text.pdf.PdfReader PDFreader = new iTextSharp.text.pdf.PdfReader(fileName);
PDFreader.ConsolidateNamedDestinations();
for (int i = 1; i <= PDFreader.NumberOfPages; i++)
{
iTextSharp.text.pdf.PdfImportedPage page = PDFwriter.GetImportedPage(PDFreader, i);
PDFwriter.AddPage(page);
}
iTextSharp.text.pdf.PRAcroForm form = PDFreader.AcroForm;
if (form != null)
{
PDFwriter.CopyAcroForm(PDFreader);
}
PDFreader.Close();
}
PDFwriter.Close();
PDFdoc.Close();
}
}

Categories