In my case, I need to let the user shoose the folder and the file name.
I know that I have to make some changes to "PdfWriterGetInstance".
Then how can I change my code to make it as I want:
Document doc = new Document(iTextSharp.text.PageSize.A4, 10, 10, 42, 35);
PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("Stock.pdf", FileMode.Create));
doc.Open();
Paragraph paragraphe = new Paragraph("Raport of Stock\n\n");
paragraphe.Alignment = Element.ALIGN_CENTER;
doc.Add(paragraphe);
DateTime now = new DateTime();
Paragraph paragraphe3 = new Paragraph(" " + now.ToString()+"\n\n\n");
paragraphe.Alignment = Element.ALIGN_LEFT;
doc.Add(paragraphe3);
PdfPTable table = new PdfPTable(dataGridView1.Columns.Count);
//add the header
for (int j=0; j < dataGridView1.Columns.Count; j++)
{
table.AddCell(new Phrase(dataGridView1.Columns[j].HeaderText));
}
//Flag the first row as a header
table.HeaderRows = 1;
for(int i = 0; i< dataGridView1.Rows.Count; i++)
{
for(int k = 0; k < dataGridView1.Columns.Count; k++)
{
if (dataGridView1[k, i].Value != null)
{
table.AddCell(new Phrase(dataGridView1[k, i].Value.ToString()));
}
}
}
doc.Add(table);
Paragraph paragraphe1 = new Paragraph(" " + "Total items: " +quaq1.ToString());
paragraphe.Alignment = Element.ALIGN_LEFT;
doc.Add(paragraphe1);
Paragraph paragraphe2 = new Paragraph(" " + "Total Price: " + tot1.ToString());
paragraphe.Alignment = Element.ALIGN_LEFT;
doc.Add(paragraphe2);
doc.Close();
Rq: I'm using iTextSharp Assembly.
I'm currently attempting to use datagridview for the first time, I have managed to do many things with it so far (such as importing text files) however, I have trouble when attempting to save the datagridview's contents to a text file.
The output I'm currently getting is:
0,
Cat,
Yes,
10,
20,
30,
40,
50,
1,
Dog,
No,
10,
20,
30,
40,
50,
I want the export to look like this:
0, Cat, Yes, 10, 20, 30, 40, 50
1, Dog, No, 10, 20, 30, 40, 50
etc.
This is the code I'm currently using:
using (TextWriter tw = new StreamWriter("example.txt"))
{
for(int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for(int j = 0; j < dataGridView1.Columns.Count; j++)
{
tw.WriteLine($"{dataGridView1.Rows[i].Cells[j].Value.ToString()},");
}
}
}
Anyone here able to help me with this issue? Thank you!
Try the following changes tw.Write() insted of tw.WriteLine():
using (TextWriter tw = new StreamWriter("example.txt"))
{
for(int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for(int j = 0; j < dataGridView1.Columns.Count; j++)
{
tw.Write($"{dataGridView1.Rows[i].Cells[j].Value.ToString()}");
if(!j == dataGridView1.Columns.Count - 1)
{
tw.Write(",");
}
}
tw.WriteLine();
}
}
So, DGV to Text file? This is how I do it.
private void button1_Click(object sender, EventArgs e)
{
//This line of code creates a text file for the data export.
System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\\your_path_here\\sample.txt");
try
{
string sLine = "";
//This for loop loops through each row in the table
for (int r = 0; r <= dataGridView1.Rows.Count - 1; r++)
{
//This for loop loops through each column, and the row number
//is passed from the for loop above.
for (int c = 0; c <= dataGridView1.Columns.Count - 1; c++)
{
sLine = sLine + dataGridView1.Rows[r].Cells[c].Value;
if (c != dataGridView1.Columns.Count - 1)
{
//A comma is added as a text delimiter in order
//to separate each field in the text file.
//You can choose another character as a delimiter.
sLine = sLine + ",";
}
}
//The exported text is written to the text file, one line at a time.
file.WriteLine(sLine);
sLine = "";
}
file.Close();
System.Windows.Forms.MessageBox.Show("Export Complete.", "Program Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception err)
{
System.Windows.Forms.MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
file.Close();
}
}
Use tw.Write() instead of tw.WriteLine() until you are finished with all but the last column for the row, then you tw.WriteLine() on the last column data to end the line.
I don't work in C#, but often use these forums as a reference. I develop interfaces for industrial applications. Anyway, the simplest way to do this is through the clipboard. Use the SelectAll() method on your DGV, Throw that DGV data into the Clipboard with the Clipboard.SetDataObject() method, use the File.WriteAllText(), and Clipboard.GetText() methods to write the clipboard text to a file. My code is below. You will notice I have to write out everything from it's namespace so I apologize for it not being exactly how C# is. Note: If you want to make a csv file, DGVs view cell breaks as horizontal tabs (ascii 9). You can do a replace() method for commas. Note: DGV.ClearSelection() is a nice way to finish it off. Note: you may have to enable ClipboardCopyMode on your DGV.
DataGridView1.SelectAll();
System.Windows.Forms.Clipboard.SetDataObject(DataGridView1.GetClipboardContent());
System.IO.File.WriteAllText("File.txt",System.Windows.Forms.Clipboard.GetText());
With the following code you can save and restore the content of every dataGridView.
How to do it:
string sContent = "";
private void btnSaveDataGridViewContent_Click(object sender, EventArgs e)
{
sContent = ReadStringFromDataGridView(ref dataGridView1);
[Write sContent to File/Database/Whatever]
}
private void btnRestoreDataGridViewContent_Click(object sender, EventArgs e)
{
[Read sContent from File/Database/Whatever]
WriteStringToDataGridView(ref dataGridView1, sContent);
}
Helper functions:
string ReadStringFromDataGridView(ref DataGridView MyDataGridView)
{
string sContent = "";
for (int row = 0; row<MyDataGridView.RowCount; row++)
{
if (row > 0) sContent += "\r";
for (int col = 0; col<MyDataGridView.ColumnCount; col++)
{
if (col > 0) sContent += ";";
sContent += MyDataGridView[col, row].Value;
}
}
return sContent;
}
void WriteStringToDataGridView(ref DataGridView MyDataGridView, string sContent)
{
MyDataGridView.Rows.Clear();
string[] Rows = sContent.Split("\r".ToCharArray());
for (int row=0; row<Rows.Length; row++)
{
MyDataGridView.RowCount = Rows.Length;
string[] Cols = Rows[row].Split(";".ToCharArray());
for (int col=0; col<Cols.Length; col++)
{
MyDataGridView[col, row].Value = Cols[col];
}
}
}
string file = "C:\\Users\\Sangeeth\\Desktop\\Excel.txt";
using (TextWriter tw = new StreamWriter(file))
{
int i, j = 0;
for(i = 0; i < dataGridView1.Rows.Count -1; i++)
{
for (j = 0; j < dataGridView1.Columns.Count; j++)
{
tw.Write($"{dataGridView1.Rows[i].Cells[j].Value.ToString()}");
tw.Write(",");
}
tw.WriteLine(" ");
}
}
I have a new problem, I want to export a datagridview to excel and have a script searched for it. The script that I found gives me an error in this line.
"ExcelApp.Cells[i + 2, j + 1] = dgvTabelle.Rows[i].Cells[j].Value.ToString();"
The whole script looks like this!
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = "C:";
sfd.Filter = "Excel File|* .xlsx";
sfd.FileName = "Flugxyz";
sfd.Title = "Speichern von Flugdatei";
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
ExcelApp.Application.Workbooks.Add(Type.Missing);
//Storing header part in Excel
for (int i = 1; i < dgvTabelle.Columns.Count + 1; i++)
{
ExcelApp.Cells[1, i] = dgvTabelle.Columns[i - 1].HeaderText;
}
//Storing Each row and column value to excel sheet
for (int i = 0; i < dgvTabelle.Rows.Count; i++)
{
for (int j = 0; j< dgvTabelle.Columns.Count; j ++)
{
ExcelApp.Cells[i + 2, j + 1] = dgvTabelle.Rows[i].Cells[j].Value.ToString();
}
}
ExcelApp.ActiveWorkbook.SaveCopyAs(sfd.FileName.ToString());
ExcelApp.ActiveWorkbook.Saved = true;
ExcelApp.Quit();
I'm using itextSharp to export a DataTable to a pdf table. I can export the data to a pdf table using the sample code i have posted below. The DataTable contains close to 21 columns.
The first column in the pdf (DataTable) might contain similar values for any number of rows. If the data values in first column for a group of rows is similar, i want to merge the first 3 columns of those rows as one cell.
I'm having trouble modifying the code below to achieve this.
public iTextSharp.text.Table GetItextTable(DataTable dtChartData, string reportType)
{
int intCols = dtChartData.Columns.Count; //Total number of columns
int intRows = dtChartData.Rows.Count; //Total number of rows
iTextSharp.text.Table pdfTable = new iTextSharp.text.Table(intCols, intRows);
try
{
pdfTable.BorderWidth = 1;
pdfTable.Width = 100;
pdfTable.Padding = 1;
pdfTable.Spacing = 1;
/*creating table headers */
for (int i = 0; i < intCols; i++)
{
iTextSharp.text.Cell cellCols = new iTextSharp.text.Cell();
iTextSharp.text.Font ColFont = iTextSharp.text.FontFactory.GetFont("Tahoma", 07,
iTextSharp.text.Font.BOLD);
for (int l = 0; l < dtChartData.Columns.Count; l++)
{
if (dtChartData.Columns[l].ColumnName.Contains("_"))
{
dtChartData.Columns[l].ColumnName = dtChartData.Columns[l].ColumnName.Replace("_", " ");
}
}
iTextSharp.text.Chunk chunkCols = new iTextSharp.text.Chunk(dtChartData.Columns[i].ColumnName,ColFont);
cellCols.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER;
if ((chunkCols.ToString().ToLower() == "ReportDetails"))
{
cellCols.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER;
}
}
/* loop that take values from every row in datatable and insert in itextsharp table */
for (int k = 0; k < intRows; k++)
{
for (int j = 0; j < intCols; j++)
{
iTextSharp.text.Cell cellRows = new iTextSharp.text.Cell();
iTextSharp.text.Font RowFont = iTextSharp.text.FontFactory.GetFont("Tahoma", 07);
iTextSharp.text.Chunk chunkRows = new iTextSharp.text.Chunk(dtChartData.Rows[k][j].ToString(),RowFont);
cellRows.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER;
cellRows.Add(chunkRows);
pdfTable.AddCell(cellRows);
}
}
}
catch (Exception ex)
{
//error handling code here removed
}
return pdfTable;
}
Have you tried to change the Colspan?
iTextSharp.text.Cell cell = new iTextSharp.text.Cell();
cell.AddElement(new Paragraph("colspan 3"));
cell.Colspan = 3;
table.AddCell(cell);
In this case, cell will span three columns.
try this. i just edited your code, not checked
here i have edited 1 line of your code and added a new line (total 2 lines of change only).
dont forget to combine headding row like this, if you need
/* loop that take values from every row in datatable and insert in itextsharp table */
for (int k = 0; k < intRows; k++)
{
for (int j = 2; j < intCols; j++)// EDIT: if all first 3 cols are same, then starts with 2
{
iTextSharp.text.Cell cellRows = new iTextSharp.text.Cell();
if(j == 2) cellRows.Colspan = 3;// ADD: it'll gives a 3 times long cell
iTextSharp.text.Font RowFont = iTextSharp.text.FontFactory.GetFont("Tahoma", 07);
iTextSharp.text.Chunk chunkRows = new iTextSharp.text.Chunk(dtChartData.Rows[k][j].ToString(),RowFont);
cellRows.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER;
cellRows.Add(chunkRows);
pdfTable.AddCell(cellRows);
}
}
I'm trying to export my datagridview to PDF however while doing that I want to group the rows which have the same Group name.
The code I use to export to pdf is at the below;
private void PrintReport_Click(object sender, EventArgs e)
{
try
{
//create iTextSharp table
PdfPTable pdfTable = new PdfPTable(dataGridView1.ColumnCount);
pdfTable.DefaultCell.Padding = 3;
pdfTable.WidthPercentage = 30;
pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
pdfTable.DefaultCell.BorderWidth = 1;
//Adding Header row
PdfPCell cell = new PdfPCell(new Phrase("Report"));
cell.Colspan = 11;
cell.BackgroundColor = new iTextSharp.text.Color(50, 50, 120);
cell.HorizontalAlignment = 1;
pdfTable.TotalWidth = 1200f;
pdfTable.LockedWidth = true;
pdfTable.AddCell(cell);
pdfTable.AddCell("Group");
pdfTable.AddCell("Numara");
pdfTable.AddCell("Müşteri ID");
pdfTable.AddCell("Tanım");
pdfTable.AddCell("IP Adresi");
pdfTable.AddCell("Kullanıcı");
pdfTable.AddCell("Şifre");
pdfTable.AddCell("Domain");
pdfTable.AddCell("2.IP");
pdfTable.AddCell("2.Kullanıcı");
pdfTable.AddCell("2.Kullanıcı Şifre");
//Adding DataRow
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
if (dataGridView1.Rows[i].Cells[j].Value != null)
{
if (j == 6|| j == 10)
{
pdfTable.AddCell("*****");
}
else if(j==0)
{
pdfTable.AddCell(dataGridView1.Rows[i].Cells[6].Value.ToString());
}
else if(j==6)
{
pdfTable.AddCell(dataGridView1.Rows[i].Cells[0].Value.ToString());
}
else
{
pdfTable.AddCell(dataGridView1.Rows[i].Cells[j - 1].Value.ToString());
}
}
else
{
pdfTable.AddCell(" ");
}
}
}
//pdfTable.AddCell(cells.Value.ToString());
//Exporting to PDF
string folderPath = "C:\\PDFs\\";
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
using (FileStream stream = new FileStream(folderPath + "Rapor.pdf", FileMode.Create))
{
Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
PdfWriter.GetInstance(pdfDoc, stream);
pdfDoc.Open();
pdfDoc.Add(pdfTable);
pdfDoc.Close();
stream.Close();
}
MessageBox.Show("C:\\PDFs uzantısına rapor kaydedildi!");
}
catch (Exception msg)
{
MessageBox.Show(msg.Message, "Error");
}
}
Code works pretty well, it exports the datagridview to pdf file but it does not work the way I want, It does not group columns by 'Group Name'
I'm stuck in this problem any help would be appreciated.
Can you just sort the results, create a pdfTable for each 'group' that has data?
I have solved the problem with a little trick, I have listed all the groups in a list named 'testlist' So I can manage the handle the sutiation within 1 pdfTable
There is the code snippet:
for (int element = 0; element < testList.Count;element++ )
{
string name = testList.ElementAt(element).ToString();
PdfPCell cell1 = new PdfPCell(new Phrase(name));
cell1.BackgroundColor = new iTextSharp.text.Color(160, 160, 210);
cell1.Colspan = 11;
cell1.HorizontalAlignment = 1;
pdfTable.AddCell(cell1);
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
if (dataGridView1.Rows[i].Cells[j].Value != null)
{
if(dataGridView1.Rows[i].Cells[6].Value.ToString() == name.ToString())
{
if (j == 6 || j == 10)
{
pdfTable.AddCell("*****");
}
else if (j == 0)
{
pdfTable.AddCell(dataGridView1.Rows[i].Cells[6].Value.ToString());
}
else if (j == 6)
{
pdfTable.AddCell(dataGridView1.Rows[i].Cells[0].Value.ToString());
}
else
{
pdfTable.AddCell(dataGridView1.Rows[i].Cells[j - 1].Value.ToString());
}
}
}
else
{
pdfTable.AddCell(" ");
}
}
}
}