// The function that print a bunch of rows that fit in one page // When it returns true, meaning that there are more rows still not printed, so another PagePrint action is required // When it returns false, meaning that all rows are printed (the CureentRow parameter reaches the last row of the DataGridView control) and no further PagePrint action is required private bool DrawRows(Graphics g, Font RowFont) { // Setting the LinePen that will be used to draw lines and rectangles (derived from the GridColor property of the DataGridView control) using (Pen penChenar = new Pen(this.lPaleta.CuloareTrasareLiniiTabel, 1)) { // The style paramters that will be used to print each cell using (SolidBrush RowForeBrush = new SolidBrush(this.lPaleta.CuloareTextTabel), RowBackBrush = new SolidBrush(Color.White), RowAlternatingBackBrush = new SolidBrush(this.lPaleta.CuloareFundalLinieAlternanta), RowAlternatingForeBrush = new SolidBrush(this.lPaleta.CuloareTextLinieAlternanta)) { // Setting the format that will be used to print each cell StringFormat CellFormat = new StringFormat(); CellFormat.Trimming = StringTrimming.Word; CellFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit; // Printing each visible cell RectangleF RowBounds; float CurrentX; float ColumnWidth; int indexLinie = 0; bool liniePara = false; bool primaColoana = false; bool ultimaColoana = false; while (CurrentRow < listaIndecsiLiniiSelectate.Count)// lDGVdePrintat.Rows.Count) { indexLinie = listaIndecsiLiniiSelectate[CurrentRow]; liniePara = CurrentRow % 2 == 1; primaColoana = true; ultimaColoana = false; //if (lDGVdePrintat.Rows[CurrentRow].Visible) // Print the cells of the CurrentRow only if that row is visible //{ // Setting the row font style //RowFont = lDGVdePrintat.Rows[indexLinie].DefaultCellStyle.Font; //if (RowFont == null) // If the there is no special font style of the CurrentRow, then use the default one associated with the DataGridView control // RowFont = lDGVdePrintat.DefaultCellStyle.Font; //// Setting the RowFore style //RowForeColor = lDGVdePrintat.Rows[indexLinie].DefaultCellStyle.ForeColor; //if (RowForeColor.IsEmpty) // If the there is no special RowFore style of the CurrentRow, then use the default one associated with the DataGridView control // RowForeColor = lDGVdePrintat.DefaultCellStyle.ForeColor; //RowForeBrush = new SolidBrush(RowForeColor); //// Setting the RowBack (for even rows) and the RowAlternatingBack (for odd rows) styles //RowBackColor = lDGVdePrintat.Rows[indexLinie].DefaultCellStyle.BackColor; //if (RowBackColor.IsEmpty) // If the there is no special RowBack style of the CurrentRow, then use the default one associated with the DataGridView control //{ // RowBackBrush = new SolidBrush(lDGVdePrintat.DefaultCellStyle.BackColor); // RowAlternatingBackBrush = new SolidBrush(lDGVdePrintat.AlternatingRowsDefaultCellStyle.BackColor); //} //else // If the there is a special RowBack style of the CurrentRow, then use it for both the RowBack and the RowAlternatingBack styles //{ // RowBackBrush = new SolidBrush(RowBackColor); // RowAlternatingBackBrush = new SolidBrush(RowBackColor); //} // Calculating the starting x coordinate that the printing process will start from CurrentX = (float)LeftMargin; if (IsCenterOnPage) { CurrentX += (((float)PageWidth - (float)RightMargin - (float)LeftMargin) - mColumnPointsWidth[mColumnPoint]) / 2.0F; } // Calculating the entire CurrentRow bounds RowBounds = new RectangleF(CurrentX, CurrentY, mColumnPointsWidth[mColumnPoint], RowsHeight[listaIndecsiLiniiSelectate[CurrentRow]]); // Filling the back of the CurrentRow if (liniePara) { g.FillRectangle(RowAlternatingBackBrush, RowBounds); } else { g.FillRectangle(RowBackBrush, RowBounds); } // Printing each visible cell of the CurrentRow for (int CurrentCell = (int)mColumnPoints[mColumnPoint].GetValue(0); CurrentCell < (int)mColumnPoints[mColumnPoint].GetValue(1); CurrentCell++) { //if (!lDGVdePrintat.Columns[CurrentCell].Visible) continue; // If the cell is belong to invisible column, then ignore this iteration if (!listaIndecsiColoanePrint.Contains(CurrentCell)) { continue; } ultimaColoana = (CurrentCell == Convert.ToInt32(mColumnPoints[mColumnPoint].GetValue(1)) - 1); // Check the CurrentCell alignment and apply it to the CellFormat if (this.lDGVdePrintat.Columns[this.lListaColoaneImprimare[CurrentCell]].DefaultCellStyle.Alignment.ToString().Contains("Right")) { CellFormat.Alignment = StringAlignment.Far; } else if (this.lDGVdePrintat.Columns[this.lListaColoaneImprimare[CurrentCell]].DefaultCellStyle.Alignment.ToString().Contains("Center")) { CellFormat.Alignment = StringAlignment.Center; } else { CellFormat.Alignment = StringAlignment.Near; } ColumnWidth = ColumnsWidth[CurrentCell]; RectangleF chenarCelula = new RectangleF(CurrentX, CurrentY, ColumnWidth, RowsHeight[indexLinie]); // Printing the cell text g.DrawString(CUtil.ConvertObjectToString(this.lDGVdePrintat.Rows[indexLinie].Cells[this.lListaColoaneImprimare[CurrentCell]].EditedFormattedValue, false), RowFont, (liniePara ? RowAlternatingForeBrush : RowForeBrush), chenarCelula, CellFormat); // Drawing the cell bounds if (lDGVdePrintat.CellBorderStyle != DataGridViewCellBorderStyle.None) // Draw the cell border only if the CellBorderStyle is not None { deseneazaCelula(g, penChenar, chenarCelula, primaColoana, ultimaColoana, CurrentX, chenarCelula.Width, RowsHeight[indexLinie]); //if (this.lPaleta.DeseneazaSeparatoriColoane) // g.DrawRectangle(penChenar, CurrentX, CurrentY, ColumnWidth, RowsHeight[indexLinie]); //else //{ // //sus // g.DrawLine(penChenar, chenarCelula.Location, new PointF(chenarCelula.X + chenarCelula.Width, chenarCelula.Y)); // if (primaColoana) // { // //stanga // g.DrawLine(penChenar, chenarCelula.Location, new PointF(chenarCelula.X, chenarCelula.Y + chenarCelula.Height)); // } // //jos // g.DrawLine(penChenar, new PointF(chenarCelula.X, chenarCelula.Y + chenarCelula.Height), new PointF(chenarCelula.X + chenarCelula.Width, chenarCelula.Y + chenarCelula.Height)); // if (ultimaColoana) // { // //dreapta // g.DrawLine(penChenar, new PointF(chenarCelula.X + chenarCelula.Width, chenarCelula.Y), new PointF(chenarCelula.X + chenarCelula.Width, chenarCelula.Y + chenarCelula.Height)); // } //} } CurrentX += ColumnWidth; primaColoana = false; } CurrentY += RowsHeight[indexLinie]; // Checking if the CurrentY is exceeds the page boundries // If so then exit the function and returning true meaning another PagePrint action is required if ((int)CurrentY > (PageHeight - TopMargin - BottomMargin)) { CurrentRow++; return(true); } //} CurrentRow++; } CurrentRow = 0; mColumnPoint++; // Continue to print the next group of columns if (!string.IsNullOrEmpty(this.lFooter)) { RectangleF HeaderRectangle = new RectangleF((float)LeftMargin, CurrentY, (float)PageWidth - (float)RightMargin - (float)LeftMargin, g.MeasureString(this.lFooter, RowFont).Height); SizeF marimeNecesara = g.MeasureString(this.lFooter, RowFont, PageWidth); using (Brush brushTitlu = new SolidBrush(TheTitleColor)) { g.DrawString(this.lFooter, RowFont, brushTitlu, HeaderRectangle); } CurrentY += 2 * marimeNecesara.Height; } if (mColumnPoint == mColumnPoints.Count) // Which means all columns are printed { mColumnPoint = 0; return(false); } else { return(true); } } } }
/// <summary> /// Export the DataGridView to Comma Separated Value file. /// This method should be used with the methods: /// CsvThread(). /// GetCsvReady(). /// </summary> /// <param name="dGV">Extended DataGridView.</param> /// <param name="filename">Full path & name of the Name of csv file.</param> void ToCsV(DataGridViewPersonalizat dGV, string filename) { if (string.IsNullOrEmpty(filename)) { return; } string valoareCelula = string.Empty; using (StreamWriter myFile = new StreamWriter(filename, false, Encoding.Default)) { //IMPORTANT!!! //Separatorul CVS pentru tarile europene este ; si nu , care este rezervat pentru zecimale myFile.WriteLine(this.lDenumireDocument); // Export only visible columns. //if (dGV.ExportVisibleColumnsOnly) //{ // Export titles: StringBuilder sHeaders = new StringBuilder(); List <int> listaIndecsiColoaneExportabile = new List <int>(); string[] culturiVirgula = { "ar-JO", "ar-SY", "az-Cyrl-AZ", "az-Latn-AZ", "zh-CN", "zh-SG", "zh-TW", "nl-BE", "nl-NL", "en-BZ", "en-CA", "en-NZ", "en-US", "fr-CA", "ms-BN", "ms-MY", "nb-NO", "nn-NO", "pt-BR", "sr-Cyrl-CS", "sr-Latn-CS", "es-AR", "es-DO", "es-MX", "es-ES_tradnl", "sv-FI", "sv-SE", "uz-Cyrl-UZ", "uz-Latn-UZ" }; string separator = "; "; if (culturiVirgula.Contains <string>(CultureInfo.CurrentCulture.Name)) { separator = ", "; } for (int j = 0; j < dGV.Columns.Count; j++) { if (dGV.Columns[j].Visible && !dGV.SeIgnoraColoanaLaImprimare(dGV.Columns[j].Name)) { valoareCelula = CUtil.InlocuiesteDiacritice(dGV.Columns[j].HeaderText); sHeaders.Append(valoareCelula); sHeaders.Append(separator); listaIndecsiColoaneExportabile.Add(j); //pentru a exporta datele coloanelor pretabile pentru export } } myFile.WriteLine(sHeaders); sHeaders = null; // Export data. //Fie cele bifate, fie toate List <DataGridViewRow> listaLiniiSelectate = dGV.GetListaLiniiSelectate(); foreach (DataGridViewRow linie in listaLiniiSelectate) { if (linie.Tag == null) { continue; //in Tag-ul tuturor liniilor din aplicatie salvam obiectul corespunzator liniei respective; lipsa acestuia implica ignorarea liniei } StringBuilder stLine = new StringBuilder(); for (int j = 0; j < linie.Cells.Count; j++) { if (listaIndecsiColoaneExportabile.Contains(j)) { stLine.Append(CUtil.ConvertObjectToString(linie.Cells[j].EditedFormattedValue, true)); stLine.Append(separator); } } myFile.WriteLine(stLine); } //} //else //{ // // Export titles: // string sHeaders = ""; // for (int j = 0; j < dGV.Columns.Count; j++) { sHeaders = sHeaders.ToString() + dGV.Columns[j].HeaderText + ", "; } // myFile.WriteLine(sHeaders); // // 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() + dGV.Rows[i].Cells[j].Value + ", "; } // myFile.WriteLine(stLine); // } //} } IHMUtile.PornesteProces(filename); }
public static void Exporta(DataGridViewPersonalizat dGV, List <string> pListaColoaneImprimare, string pEtichetaTotal, string pFisier, bool pDeschideDupaCreare) { string fisierSalvare = pFisier; DataType tipCelula = DataType.String; if (string.IsNullOrEmpty(fisierSalvare)) { fisierSalvare = CCL.UI.IHMUtile.GetCaleSalvareFisier(CCL.UI.IHMUtile.GetFormParinte(dGV), ".xls"); } if (string.IsNullOrEmpty(fisierSalvare)) { return; } string idStilHeader = "idSHeader"; WorksheetStyle stilHeader = new WorksheetStyle(idStilHeader); stilHeader.Font.Bold = true; stilHeader.Interior.Pattern = StyleInteriorPattern.Solid; stilHeader.Interior.Color = "#c0c0c0"; string idStilTotal = "idSTotal"; WorksheetStyle stilTotal = new WorksheetStyle(idStilTotal); stilTotal.Font.Bold = true; stilTotal.Interior.Pattern = StyleInteriorPattern.Solid; stilTotal.Interior.Color = "#80ff80"; string idStilNormal = "idSNormal"; WorksheetStyle stilNormal = new WorksheetStyle(idStilNormal); Workbook book = new Workbook(); book.Styles.Add(stilHeader); book.Styles.Add(stilNormal); book.Styles.Add(stilTotal); Worksheet sheet = book.Worksheets.Add("iDava"); List <string> listaNumeColoaneExportabile = new List <string>(); Dictionary <string, DataType> dictColoaneTipuri = new Dictionary <string, DataType>(); string valoareCelula = string.Empty; WorksheetRow rowHeader = sheet.Table.Rows.Add(); foreach (string numeColoana in pListaColoaneImprimare) { if (dGV.Columns[numeColoana].Visible && !dGV.SeIgnoraColoanaLaImprimare(numeColoana)) { listaNumeColoaneExportabile.Add(numeColoana); //pentru a exporta datele coloanelor pretabile pentru export dictColoaneTipuri.Add(numeColoana, getDataType(dGV.Columns[numeColoana])); valoareCelula = CUtil.InlocuiesteDiacritice(dGV.Columns[numeColoana].HeaderText); rowHeader.Cells.Add(valoareCelula, dictColoaneTipuri[numeColoana], idStilHeader); } } List <DataGridViewRow> listaLiniiSelectate = dGV.GetListaLiniiSelectate(); bool existaValoareNumerica = false; double totalValoareNumerica = 0; foreach (DataGridViewRow linie in listaLiniiSelectate) { if (linie.Tag == null) { continue; //in Tag-ul tuturor liniilor din aplicatie salvam obiectul corespunzator liniei respective; lipsa acestuia implica ignorarea liniei } WorksheetRow rowValoare = sheet.Table.Rows.Add(); foreach (string numeColoane in pListaColoaneImprimare) { if (listaNumeColoaneExportabile.Contains(numeColoane)) { if (linie.Cells[numeColoane].Tag != null && linie.Cells[numeColoane].Tag is String) { valoareCelula = CUtil.ConvertObjectToString(linie.Cells[numeColoane].Tag, true); } else { valoareCelula = CUtil.ConvertObjectToString(linie.Cells[numeColoane].EditedFormattedValue, true); } if (dGV.esteColoanaNumericaExport(numeColoane)) { existaValoareNumerica = true; totalValoareNumerica += CUtil.GetAsDouble(valoareCelula); rowValoare.Cells.Add(valoareCelula, dictColoaneTipuri[numeColoane], idStilNormal); } else { rowValoare.Cells.Add(valoareCelula, dictColoaneTipuri[numeColoane], idStilNormal); } } } } if (existaValoareNumerica) { WorksheetRow rowValoare = sheet.Table.Rows.Add(); int indexCelula = 0; foreach (string numeColoane in pListaColoaneImprimare) { if (listaNumeColoaneExportabile.Contains(numeColoane)) { if (dGV.esteColoanaNumericaExport(numeColoane)) { rowValoare.Cells.Add(Convert.ToString(Math.Round(totalValoareNumerica, 2)), dictColoaneTipuri[numeColoane], idStilTotal); } else { if (indexCelula == 0) { rowValoare.Cells.Add(pEtichetaTotal, tipCelula, idStilTotal); } else { rowValoare.Cells.Add(string.Empty, tipCelula, idStilTotal); } indexCelula += 1; } } } } if (!string.IsNullOrEmpty(fisierSalvare)) { book.Save(fisierSalvare); if (pDeschideDupaCreare) { Process.Start(fisierSalvare); } } }