• C#编程笔记(三)


    实在睡不着,整理下以前项目的代码。

    跟着项目代码来的,可能略琐碎,见谅。贴了较多代码,只为方便自己以后再用的时候查阅。

    1、Excel与Datatable的互操作,相互导入导出。

    简单地说,Excel的表结构与DataTable,以及包含了DataTable的DataGridView,格式上是一样的,相互导入导出,就是对齐格式,然后从源拷贝ElementItem的内容到目标Item。

    >DataGridView中的数据导出至Excel

    DateGridViewExportToExcel
     1         // 公用函数 将选定的DataGridView中的内容,输出到Excel表中
     2         public void DateGridViewExportToExcel(DataGridView dataGridView1)
     3         {
     4             //导出到execl  
     5             try
     6             {
     7                 //没有数据的话就不往下执行  
     8                 if (dataGridView1.Rows.Count == 0)
     9                     return;
    10                 //实例化一个Excel.Application对象  
    11                 Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
    12 
    13                 //让后台执行设置为不可见,为true的话会看到打开一个Excel,然后数据在往里写  
    14                 excel.Visible = false;
    15 
    16                 //新增加一个工作簿,Workbook是直接保存,不会弹出保存对话框,加上Application会弹出保存对话框,值为false会报错  
    17                 excel.Application.Workbooks.Add(true);
    18                 //生成Excel中列头名称  
    19                 for (int i = 0; i < dataGridView1.Columns.Count; i++)
    20                 {
    21                     excel.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;
    22                 }
    23                 //把DataGridView当前页的数据保存在Excel中  
    24                 for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
    25                 {
    26                     for (int j = 0; j < dataGridView1.Columns.Count; j++)
    27                     {
    28                         if (dataGridView1[j, i].ValueType == typeof(string))
    29                         {
    30                             excel.Cells[i + 2, j + 1] = "'" + dataGridView1[j, i].Value.ToString();
    31                         }
    32                         else
    33                         {
    34                             excel.Cells[i + 2, j + 1] = dataGridView1[j, i].Value.ToString();
    35                         }
    36                     }
    37                 }
    38 
    39                 //自动调整列宽
    40                 excel.Columns.AutoFit();
    41                 //设置禁止弹出保存和覆盖的询问提示框  
    42                 excel.DisplayAlerts = false;
    43                 excel.AlertBeforeOverwriting = false;
    44 
    45                 //保存工作簿  
    46                 //excel.Application.Workbooks.Add(true).Save();
    47                 //保存excel文件  
    48                 excel.Save(@".\temp.xls");
    49 
    50                 //确保Excel进程关闭  
    51                 excel.Quit();
    52                 excel = null;
    53 
    54             }
    55             catch (Exception ex)
    56             {
    57                 MessageBox.Show(ex.Message, "错误提示");
    58             }
    59         }

    >DataTable中的数据导出至Excel

    DataTableExportToExcel
     1         // 公用函数 将选定DataTable中的内容,输出到Excel表中
     2         private void DataTableExportToExcel(string msql)
     3         {
     4             System.Data.DataTable _table = GetDataTable(msql);
     5             //导出到execl  
     6             try
     7             {
     8                 //没有数据的话就不往下执行  
     9                 if (_table.Rows.Count == 0)
    10                 {
    11                     MessageBox.Show("表中没有数据");
    12                     return;
    13                 }
    14                 //实例化一个Excel.Application对象  
    15                 Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
    16 
    17                 //让后台执行设置为不可见,为true的话会看到打开一个Excel,然后数据在往里写  
    18                 excel.Visible = false;
    19 
    20                 //新增加一个工作簿,Workbook是直接保存,不会弹出保存对话框,加上Application会弹出保存对话框,值为false会报错  
    21                 excel.Application.Workbooks.Add(true);
    22                 //生成Excel中列头名称  
    23                 for (int i = 0; i < _table.Columns.Count; i++)
    24                 {
    25                     excel.Cells[1, i + 1] = _table.Columns[i].ColumnName;
    26                 }
    27                 //把DataGridView当前页的数据保存在Excel中  
    28                 for (int i = 0; i < _table.Rows.Count; i++)
    29                 {
    30                     for (int j = 0; j < _table.Columns.Count; j++)
    31                     {
    32                         if (_table.Columns[j].DataType == typeof(string))
    33                         {
    34                             excel.Cells[i + 2, j + 1] = "'" + _table.Rows[i].ItemArray[j].ToString();
    35                         }
    36                         else
    37                         {
    38                             excel.Cells[i + 2, j + 1] = _table.Rows[i].ItemArray[j].ToString();
    39                         }
    40                     }
    41                 }
    42 
    43                 //设置禁止弹出保存和覆盖的询问提示框  
    44                 excel.DisplayAlerts = false;
    45                 excel.AlertBeforeOverwriting = false;
    46 
    47                 //保存工作簿  
    48                 //excel.Application.Workbooks.Add(true).Save();
    49 
    50                 //保存excel文件  
    51                 excel.Save(@".\temp.xls");
    52 
    53                 //确保Excel进程关闭  
    54                 excel.Quit();
    55                 excel = null;
    56 
    57                 MessageBox.Show("备份完毕");
    58 
    59             }
    60             catch (Exception ex)
    61             {
    62                 MessageBox.Show(ex.Message, "错误提示");
    63             }
    64         }

    >Excel中的数据导入至Datatable

    ExcelToDataTable
     1         // 公用函数 把Excel数据读入DataTable
     2         private System.Data.DataTable ExcelToDataTable(string strExcelFileName, string strSheetName)
     3         {
     4             string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strExcelFileName + ";" + "Extended Properties=Excel 5.0;";
     5             string strExcel = string.Format("select * from [{0}$]", strSheetName);
     6             DataSet ds = new DataSet();
     7 
     8             using (OleDbConnection conn = new OleDbConnection(strConn))
     9             {
    10                 conn.Open();
    11                 OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn);
    12                 adapter.Fill(ds, strSheetName);
    13                 conn.Close();
    14             }
    15 
    16             return ds.Tables[strSheetName];
    17         }

    以上对于一般的数据库导入导出Excel表,差不多够用了。

    2、ComboBox的数据绑定

    ComboBox数据绑定
    1             SqlDataAdapter dataAdapter2 = new SqlDataAdapter(msql2, ConfigurationManager.ConnectionStrings["OMHMS_Leader.Properties.Settings.OMHMSConnectionString"].ConnectionString);
    2             DataSet ds2 = new DataSet();
    3             dataAdapter2.Fill(ds2);
    4             this._cbLine.DataSource = ds2.Tables[0].DefaultView;
    5             this._cbLine.DisplayMember = "Line_Name";

    3、数据绑定到DataGridView

    自己在做这种报表数据显示的时候,用了较多的DataGridView,积累下来实现了,只传入SQL语句或者存储过程,即可显示指定的数据。以某一个获取员工信息的方法为例。

    GetData
     1         // 公用函数 datagridview 数据填充函数
     2         private void GetData(string selectCommand, BindingSource bd)
     3         {
     4             try
     5             {
     6                 // Specify a connection string. Replace the given value with a 
     7                 // valid connection string for a Northwind SQL Server sample
     8                 // database accessible to your system.
     9 
    10                 // Create a new data adapter based on the specified query.
    11                 SqlDataAdapter dataAdapter = new SqlDataAdapter(selectCommand, ConfigurationManager.ConnectionStrings["OMHMS_Leader.Properties.Settings.OMHMSConnectionString"].ConnectionString);
    12 
    13                 // Create a command builder to generate SQL update, insert, and
    14                 // delete commands based on selectCommand. These are used to
    15                 // update the database.
    16                 SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
    17 
    18                 // Populate a new data table and bind it to the BindingSource.
    19                 System.Data.DataTable table = new System.Data.DataTable();
    20                 table.Locale = System.Globalization.CultureInfo.InvariantCulture;
    21                 dataAdapter.Fill(table);
    22                 bd.DataSource = table;
    23 
    24             }
    25             catch (Exception ex)
    26             {
    27                 MessageBox.Show("出现错误,错误原因为" + ex.Message,
    28                     "系统提示:", MessageBoxButtons.OK, MessageBoxIcon.Error);
    29             }
    30         }
    SampleDataBinding
     1         private void dGVStaffRefresh()
     2         {
     3             string msql = "select Staff_Cid,Staff_Sid,Staff_Name,Staff_Department,Staff_Line,Staff_Process from OMHMS_Staffs";
     4             BindingSource bs8 = new BindingSource();
     5             this._dGVStaff.DataSource = bs8;
     6             GetData(msql, bs8);
     7 
     8             this._dGVStaff.Columns[0].Width = (int)(this._dGVStaff.Width * 0.1);
     9             this._dGVStaff.Columns[1].Width = (int)(this._dGVStaff.Width * 0.1);
    10             this._dGVStaff.Columns[2].Width = (int)(this._dGVStaff.Width * 0.2);
    11             this._dGVStaff.Columns[3].Width = (int)(this._dGVStaff.Width * 0.2);
    12             this._dGVStaff.Columns[4].Width = (int)(this._dGVStaff.Width * 0.2);
    13             this._dGVStaff.Columns[5].Width = (int)(this._dGVStaff.Width * 0.2);
    14 
    15             this._dGVStaff.Columns[0].HeaderText = "卡号";
    16             this._dGVStaff.Columns[1].HeaderText = "工号";
    17             this._dGVStaff.Columns[2].HeaderText = "姓名";
    18             this._dGVStaff.Columns[3].HeaderText = "部门";
    19             this._dGVStaff.Columns[4].HeaderText = "生产线";
    20             this._dGVStaff.Columns[5].HeaderText = "工序";
    21         }

    4、DataGridView选定后打印数据,可打印到文件或打印机。好久之前的活儿了,不记得从哪里K来的,有见过的劳驾M我,一定附上源链接,先谢过了。

    核心的是一个DataGridViewPrinter的类:

    DataGridViewPrinter
      1     class DataGridViewPrinter
      2     {
      3         private DataGridView TheDataGridView; // The DataGridView Control which will be printed
      4         private PrintDocument ThePrintDocument; // The PrintDocument to be used for printing
      5         private bool IsCenterOnPage; // Determine if the report will be printed in the Top-Center of the page
      6         private bool IsWithTitle; // Determine if the page contain title text
      7         private string TheTitleText; // The title text to be printed in each page (if IsWithTitle is set to true)
      8         private Font TheTitleFont; // The font to be used with the title text (if IsWithTitle is set to true)
      9         private Color TheTitleColor; // The color to be used with the title text (if IsWithTitle is set to true)
     10         private bool IsWithPaging; // Determine if paging is used
     11 
     12         static int CurrentRow; // A static parameter that keep track on which Row (in the DataGridView control) that should be printed
     13 
     14         static int PageNumber;
     15 
     16         private int PageWidth;
     17         private int PageHeight;
     18         private int LeftMargin;
     19         private int TopMargin;
     20         private int RightMargin;
     21         private int BottomMargin;
     22 
     23         private float CurrentY; // A parameter that keep track on the y coordinate of the page, so the next object to be printed will start from this y coordinate
     24 
     25         private float RowHeaderHeight;
     26         private List<float> RowsHeight;
     27         private List<float> ColumnsWidth;
     28         private float TheDataGridViewWidth;
     29 
     30         // Maintain a generic list to hold start/stop points for the column printing
     31         // This will be used for wrapping in situations where the DataGridView will not fit on a single page
     32         private List<int[]> mColumnPoints;
     33         private List<float> mColumnPointsWidth;
     34         private int mColumnPoint;
     35 
     36         // The class constructor
     37         public DataGridViewPrinter(DataGridView aDataGridView, PrintDocument aPrintDocument, bool CenterOnPage, bool WithTitle, string aTitleText, Font aTitleFont, Color aTitleColor, bool WithPaging)
     38         {
     39             TheDataGridView = aDataGridView;
     40             ThePrintDocument = aPrintDocument;
     41             IsCenterOnPage = CenterOnPage;
     42             IsWithTitle = WithTitle;
     43             TheTitleText = aTitleText;
     44             TheTitleFont = aTitleFont;
     45             TheTitleColor = aTitleColor;
     46             IsWithPaging = WithPaging;
     47 
     48             PageNumber = 0;
     49 
     50             RowsHeight = new List<float>();
     51             ColumnsWidth = new List<float>();
     52 
     53             mColumnPoints = new List<int[]>();
     54             mColumnPointsWidth = new List<float>();
     55 
     56             // Claculating the PageWidth and the PageHeight
     57             if (!ThePrintDocument.DefaultPageSettings.Landscape)
     58             {
     59                 PageWidth = ThePrintDocument.DefaultPageSettings.PaperSize.Width;
     60                 PageHeight = ThePrintDocument.DefaultPageSettings.PaperSize.Height;
     61             }
     62             else
     63             {
     64                 PageHeight = ThePrintDocument.DefaultPageSettings.PaperSize.Width;
     65                 PageWidth = ThePrintDocument.DefaultPageSettings.PaperSize.Height;
     66             }
     67 
     68             // Claculating the page margins
     69             LeftMargin = ThePrintDocument.DefaultPageSettings.Margins.Left;
     70             TopMargin = ThePrintDocument.DefaultPageSettings.Margins.Top;
     71             RightMargin = ThePrintDocument.DefaultPageSettings.Margins.Right;
     72             BottomMargin = ThePrintDocument.DefaultPageSettings.Margins.Bottom;
     73 
     74             // First, the current row to be printed is the first row in the DataGridView control
     75             CurrentRow = 0;
     76         }
     77 
     78         // The function that calculate the height of each row (including the header row), the width of each column (according to the longest text in all its cells including the header cell), and the whole DataGridView width
     79         private void Calculate(Graphics g)
     80         {
     81             if (PageNumber == 0) // Just calculate once
     82             {
     83                 SizeF tmpSize = new SizeF();
     84                 Font tmpFont;
     85                 float tmpWidth;
     86 
     87                 TheDataGridViewWidth = 0;
     88                 for (int i = 0; i < TheDataGridView.Columns.Count; i++)
     89                 {
     90                     tmpFont = TheDataGridView.ColumnHeadersDefaultCellStyle.Font;
     91                     if (tmpFont == null) // If there is no special HeaderFont style, then use the default DataGridView font style
     92                         tmpFont = TheDataGridView.DefaultCellStyle.Font;
     93 
     94                     tmpSize = g.MeasureString(TheDataGridView.Columns[i].HeaderText, tmpFont);
     95                     tmpWidth = tmpSize.Width;
     96                     RowHeaderHeight = tmpSize.Height;
     97 
     98                     for (int j = 0; j < TheDataGridView.Rows.Count; j++)
     99                     {
    100                         tmpFont = TheDataGridView.Rows[j].DefaultCellStyle.Font;
    101                         if (tmpFont == null) // If the there is no special font style of the CurrentRow, then use the default one associated with the DataGridView control
    102                             tmpFont = TheDataGridView.DefaultCellStyle.Font;
    103 
    104                         tmpSize = g.MeasureString("Anything", tmpFont);
    105                         RowsHeight.Add(tmpSize.Height);
    106 
    107                         tmpSize = g.MeasureString(TheDataGridView.Rows[j].Cells[i].EditedFormattedValue.ToString(), tmpFont);
    108                         if (tmpSize.Width > tmpWidth)
    109                             tmpWidth = tmpSize.Width;
    110                     }
    111                     if (TheDataGridView.Columns[i].Visible)
    112                         TheDataGridViewWidth += tmpWidth;
    113                     ColumnsWidth.Add(tmpWidth);
    114                 }
    115 
    116                 // Define the start/stop column points based on the page width and the DataGridView Width
    117                 // We will use this to determine the columns which are drawn on each page and how wrapping will be handled
    118                 // By default, the wrapping will occurr such that the maximum number of columns for a page will be determine
    119                 int k;
    120 
    121                 int mStartPoint = 0;
    122                 for (k = 0; k < TheDataGridView.Columns.Count; k++)
    123                     if (TheDataGridView.Columns[k].Visible)
    124                     {
    125                         mStartPoint = k;
    126                         break;
    127                     }
    128 
    129                 int mEndPoint = TheDataGridView.Columns.Count;
    130                 for (k = TheDataGridView.Columns.Count - 1; k >= 0; k--)
    131                     if (TheDataGridView.Columns[k].Visible)
    132                     {
    133                         mEndPoint = k + 1;
    134                         break;
    135                     }
    136 
    137                 float mTempWidth = TheDataGridViewWidth;
    138                 float mTempPrintArea = (float)PageWidth - (float)LeftMargin - (float)RightMargin;
    139 
    140                 // We only care about handling where the total datagridview width is bigger then the print area
    141                 if (TheDataGridViewWidth > mTempPrintArea)
    142                 {
    143                     mTempWidth = 0.0F;
    144                     for (k = 0; k < TheDataGridView.Columns.Count; k++)
    145                     {
    146                         if (TheDataGridView.Columns[k].Visible)
    147                         {
    148                             mTempWidth += ColumnsWidth[k];
    149                             // If the width is bigger than the page area, then define a new column print range
    150                             if (mTempWidth > mTempPrintArea)
    151                             {
    152                                 mTempWidth -= ColumnsWidth[k];
    153                                 mColumnPoints.Add(new int[] { mStartPoint, mEndPoint });
    154                                 mColumnPointsWidth.Add(mTempWidth);
    155                                 mStartPoint = k;
    156                                 mTempWidth = ColumnsWidth[k];
    157                             }
    158                         }
    159                         // Our end point is actually one index above the current index
    160                         mEndPoint = k + 1;
    161                     }
    162                 }
    163                 // Add the last set of columns
    164                 mColumnPoints.Add(new int[] { mStartPoint, mEndPoint });
    165                 mColumnPointsWidth.Add(mTempWidth);
    166                 mColumnPoint = 0;
    167             }
    168         }
    169 
    170         // The funtion that print the title, page number, and the header row
    171         private void DrawHeader(Graphics g)
    172         {
    173             CurrentY = (float)TopMargin;
    174 
    175             // Printing the page number (if isWithPaging is set to true)
    176             if (IsWithPaging)
    177             {
    178                 PageNumber++;
    179                 string PageString = "Page " + PageNumber.ToString();
    180 
    181                 StringFormat PageStringFormat = new StringFormat();
    182                 PageStringFormat.Trimming = StringTrimming.Word;
    183                 PageStringFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
    184                 PageStringFormat.Alignment = StringAlignment.Far;
    185 
    186                 Font PageStringFont = new Font("Tahoma", 8, FontStyle.Regular, GraphicsUnit.Point);
    187 
    188                 RectangleF PageStringRectangle = new RectangleF((float)LeftMargin, CurrentY, (float)PageWidth - (float)RightMargin - (float)LeftMargin, g.MeasureString(PageString, PageStringFont).Height);
    189 
    190                 g.DrawString(PageString, PageStringFont, new SolidBrush(Color.Black), PageStringRectangle, PageStringFormat);
    191 
    192                 CurrentY += g.MeasureString(PageString, PageStringFont).Height;
    193             }
    194 
    195             // Printing the title (if IsWithTitle is set to true)
    196             if (IsWithTitle)
    197             {
    198                 StringFormat TitleFormat = new StringFormat();
    199                 TitleFormat.Trimming = StringTrimming.Word;
    200                 TitleFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
    201                 if (IsCenterOnPage)
    202                     TitleFormat.Alignment = StringAlignment.Center;
    203                 else
    204                     TitleFormat.Alignment = StringAlignment.Near;
    205 
    206                 RectangleF TitleRectangle = new RectangleF((float)LeftMargin, CurrentY, (float)PageWidth - (float)RightMargin - (float)LeftMargin, g.MeasureString(TheTitleText, TheTitleFont).Height);
    207 
    208                 g.DrawString(TheTitleText, TheTitleFont, new SolidBrush(TheTitleColor), TitleRectangle, TitleFormat);
    209 
    210                 CurrentY += g.MeasureString(TheTitleText, TheTitleFont).Height;
    211             }
    212 
    213             // Calculating the starting x coordinate that the printing process will start from
    214             float CurrentX = (float)LeftMargin;
    215             if (IsCenterOnPage)
    216                 CurrentX += (((float)PageWidth - (float)RightMargin - (float)LeftMargin) - mColumnPointsWidth[mColumnPoint]) / 2.0F;
    217 
    218             // Setting the HeaderFore style
    219             Color HeaderForeColor = TheDataGridView.ColumnHeadersDefaultCellStyle.ForeColor;
    220             if (HeaderForeColor.IsEmpty) // If there is no special HeaderFore style, then use the default DataGridView style
    221                 HeaderForeColor = TheDataGridView.DefaultCellStyle.ForeColor;
    222             SolidBrush HeaderForeBrush = new SolidBrush(HeaderForeColor);
    223 
    224             // Setting the HeaderBack style
    225             Color HeaderBackColor = TheDataGridView.ColumnHeadersDefaultCellStyle.BackColor;
    226             if (HeaderBackColor.IsEmpty) // If there is no special HeaderBack style, then use the default DataGridView style
    227                 HeaderBackColor = TheDataGridView.DefaultCellStyle.BackColor;
    228             SolidBrush HeaderBackBrush = new SolidBrush(HeaderBackColor);
    229 
    230             // Setting the LinePen that will be used to draw lines and rectangles (derived from the GridColor property of the DataGridView control)
    231             Pen TheLinePen = new Pen(TheDataGridView.GridColor, 1);
    232 
    233             // Setting the HeaderFont style
    234             Font HeaderFont = TheDataGridView.ColumnHeadersDefaultCellStyle.Font;
    235             if (HeaderFont == null) // If there is no special HeaderFont style, then use the default DataGridView font style
    236                 HeaderFont = TheDataGridView.DefaultCellStyle.Font;
    237 
    238             // Calculating and drawing the HeaderBounds        
    239             RectangleF HeaderBounds = new RectangleF(CurrentX, CurrentY, mColumnPointsWidth[mColumnPoint], RowHeaderHeight);
    240             g.FillRectangle(HeaderBackBrush, HeaderBounds);
    241 
    242             // Setting the format that will be used to print each cell of the header row
    243             StringFormat CellFormat = new StringFormat();
    244             CellFormat.Trimming = StringTrimming.Word;
    245             CellFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
    246 
    247             // Printing each visible cell of the header row
    248             RectangleF CellBounds;
    249             float ColumnWidth;
    250             for (int i = (int)mColumnPoints[mColumnPoint].GetValue(0); i < (int)mColumnPoints[mColumnPoint].GetValue(1); i++)
    251             {
    252                 if (!TheDataGridView.Columns[i].Visible) continue; // If the column is not visible then ignore this iteration
    253 
    254                 ColumnWidth = ColumnsWidth[i];
    255 
    256                 // Check the CurrentCell alignment and apply it to the CellFormat
    257                 if (TheDataGridView.ColumnHeadersDefaultCellStyle.Alignment.ToString().Contains("Right"))
    258                     CellFormat.Alignment = StringAlignment.Far;
    259                 else if (TheDataGridView.ColumnHeadersDefaultCellStyle.Alignment.ToString().Contains("Center"))
    260                     CellFormat.Alignment = StringAlignment.Center;
    261                 else
    262                     CellFormat.Alignment = StringAlignment.Near;
    263 
    264                 CellBounds = new RectangleF(CurrentX, CurrentY, ColumnWidth, RowHeaderHeight);
    265 
    266                 // Printing the cell text
    267                 g.DrawString(TheDataGridView.Columns[i].HeaderText, HeaderFont, HeaderForeBrush, CellBounds, CellFormat);
    268 
    269                 // Drawing the cell bounds
    270                 if (TheDataGridView.RowHeadersBorderStyle != DataGridViewHeaderBorderStyle.None) // Draw the cell border only if the HeaderBorderStyle is not None
    271                     g.DrawRectangle(TheLinePen, CurrentX, CurrentY, ColumnWidth, RowHeaderHeight);
    272 
    273                 CurrentX += ColumnWidth;
    274             }
    275 
    276             CurrentY += RowHeaderHeight;
    277         }
    278 
    279         // The function that print a bunch of rows that fit in one page
    280         // When it returns true, meaning that there are more rows still not printed, so another PagePrint action is required
    281         // 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
    282         private bool DrawRows(Graphics g)
    283         {
    284             // Setting the LinePen that will be used to draw lines and rectangles (derived from the GridColor property of the DataGridView control)
    285             Pen TheLinePen = new Pen(TheDataGridView.GridColor, 1);
    286 
    287             // The style paramters that will be used to print each cell
    288             Font RowFont;
    289             Color RowForeColor;
    290             Color RowBackColor;
    291             SolidBrush RowForeBrush;
    292             SolidBrush RowBackBrush;
    293             SolidBrush RowAlternatingBackBrush;
    294 
    295             // Setting the format that will be used to print each cell
    296             StringFormat CellFormat = new StringFormat();
    297             CellFormat.Trimming = StringTrimming.Word;
    298             CellFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit;
    299 
    300             // Printing each visible cell
    301             RectangleF RowBounds;
    302             float CurrentX;
    303             float ColumnWidth;
    304             while (CurrentRow < TheDataGridView.Rows.Count)
    305             {
    306                 if (TheDataGridView.Rows[CurrentRow].Visible) // Print the cells of the CurrentRow only if that row is visible
    307                 {
    308                     // Setting the row font style
    309                     RowFont = TheDataGridView.Rows[CurrentRow].DefaultCellStyle.Font;
    310                     if (RowFont == null) // If the there is no special font style of the CurrentRow, then use the default one associated with the DataGridView control
    311                         RowFont = TheDataGridView.DefaultCellStyle.Font;
    312 
    313                     // Setting the RowFore style
    314                     RowForeColor = TheDataGridView.Rows[CurrentRow].DefaultCellStyle.ForeColor;
    315                     if (RowForeColor.IsEmpty) // If the there is no special RowFore style of the CurrentRow, then use the default one associated with the DataGridView control
    316                         RowForeColor = TheDataGridView.DefaultCellStyle.ForeColor;
    317                     RowForeBrush = new SolidBrush(RowForeColor);
    318 
    319                     // Setting the RowBack (for even rows) and the RowAlternatingBack (for odd rows) styles
    320                     RowBackColor = TheDataGridView.Rows[CurrentRow].DefaultCellStyle.BackColor;
    321                     if (RowBackColor.IsEmpty) // If the there is no special RowBack style of the CurrentRow, then use the default one associated with the DataGridView control
    322                     {
    323                         RowBackBrush = new SolidBrush(TheDataGridView.DefaultCellStyle.BackColor);
    324                         RowAlternatingBackBrush = new SolidBrush(TheDataGridView.AlternatingRowsDefaultCellStyle.BackColor);
    325                     }
    326                     else // If the there is a special RowBack style of the CurrentRow, then use it for both the RowBack and the RowAlternatingBack styles
    327                     {
    328                         RowBackBrush = new SolidBrush(RowBackColor);
    329                         RowAlternatingBackBrush = new SolidBrush(RowBackColor);
    330                     }
    331 
    332                     // Calculating the starting x coordinate that the printing process will start from
    333                     CurrentX = (float)LeftMargin;
    334                     if (IsCenterOnPage)
    335                         CurrentX += (((float)PageWidth - (float)RightMargin - (float)LeftMargin) - mColumnPointsWidth[mColumnPoint]) / 2.0F;
    336 
    337                     // Calculating the entire CurrentRow bounds                
    338                     RowBounds = new RectangleF(CurrentX, CurrentY, mColumnPointsWidth[mColumnPoint], RowsHeight[CurrentRow]);
    339 
    340                     // Filling the back of the CurrentRow
    341                     if (CurrentRow % 2 == 0)
    342                         g.FillRectangle(RowBackBrush, RowBounds);
    343                     else
    344                         g.FillRectangle(RowAlternatingBackBrush, RowBounds);
    345 
    346                     // Printing each visible cell of the CurrentRow                
    347                     for (int CurrentCell = (int)mColumnPoints[mColumnPoint].GetValue(0); CurrentCell < (int)mColumnPoints[mColumnPoint].GetValue(1); CurrentCell++)
    348                     {
    349                         if (!TheDataGridView.Columns[CurrentCell].Visible) continue; // If the cell is belong to invisible column, then ignore this iteration
    350 
    351                         // Check the CurrentCell alignment and apply it to the CellFormat
    352                         if (TheDataGridView.Columns[CurrentCell].DefaultCellStyle.Alignment.ToString().Contains("Right"))
    353                             CellFormat.Alignment = StringAlignment.Far;
    354                         else if (TheDataGridView.Columns[CurrentCell].DefaultCellStyle.Alignment.ToString().Contains("Center"))
    355                             CellFormat.Alignment = StringAlignment.Center;
    356                         else
    357                             CellFormat.Alignment = StringAlignment.Near;
    358 
    359                         ColumnWidth = ColumnsWidth[CurrentCell];
    360                         RectangleF CellBounds = new RectangleF(CurrentX, CurrentY, ColumnWidth, RowsHeight[CurrentRow]);
    361 
    362                         // Printing the cell text
    363                         g.DrawString(TheDataGridView.Rows[CurrentRow].Cells[CurrentCell].EditedFormattedValue.ToString(), RowFont, RowForeBrush, CellBounds, CellFormat);
    364 
    365                         // Drawing the cell bounds
    366                         if (TheDataGridView.CellBorderStyle != DataGridViewCellBorderStyle.None) // Draw the cell border only if the CellBorderStyle is not None
    367                             g.DrawRectangle(TheLinePen, CurrentX, CurrentY, ColumnWidth, RowsHeight[CurrentRow]);
    368 
    369                         CurrentX += ColumnWidth;
    370                     }
    371                     CurrentY += RowsHeight[CurrentRow];
    372 
    373                     // Checking if the CurrentY is exceeds the page boundries
    374                     // If so then exit the function and returning true meaning another PagePrint action is required
    375                     if ((int)CurrentY > (PageHeight - TopMargin - BottomMargin))
    376                     {
    377                         CurrentRow++;
    378                         return true;
    379                     }
    380                 }
    381                 CurrentRow++;
    382             }
    383 
    384             CurrentRow = 0;
    385             mColumnPoint++; // Continue to print the next group of columns
    386 
    387             if (mColumnPoint == mColumnPoints.Count) // Which means all columns are printed
    388             {
    389                 mColumnPoint = 0;
    390                 return false;
    391             }
    392             else
    393                 return true;
    394         }
    395 
    396         // The method that calls all other functions
    397         public bool DrawDataGridView(Graphics g)
    398         {
    399             try
    400             {
    401                 Calculate(g);
    402                 DrawHeader(g);
    403                 bool bContinue = DrawRows(g);
    404                 return bContinue;
    405             }
    406             catch (Exception ex)
    407             {
    408                 MessageBox.Show("Operation failed: " + ex.Message.ToString(), Application.ProductName + " - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    409                 return false;
    410             }
    411         }
    412     }
    413 }

    在使用的时候,需要如下的几个方法:

    Printer Related Functions
     1         // 打印核心方法
     2         private bool SetupThePrinting(DataGridView _datagridview)
     3         {
     4             PrintDialog MyPrintDialog = new PrintDialog();
     5             MyPrintDialog.AllowCurrentPage = false;
     6             MyPrintDialog.AllowPrintToFile = false;
     7             MyPrintDialog.AllowSelection = false;
     8             MyPrintDialog.AllowSomePages = false;
     9             MyPrintDialog.PrintToFile = false;
    10             MyPrintDialog.ShowHelp = false;
    11             MyPrintDialog.ShowNetwork = false;
    12 
    13             if (MyPrintDialog.ShowDialog() != DialogResult.OK)
    14                 return false;
    15 
    16             MyPrintDocument.DocumentName = "OMH报表";
    17             MyPrintDocument.PrinterSettings = MyPrintDialog.PrinterSettings;
    18             MyPrintDocument.DefaultPageSettings = MyPrintDialog.PrinterSettings.DefaultPageSettings;
    19             MyPrintDocument.DefaultPageSettings.Margins = new Margins(40, 40, 40, 40);
    20 
    21             if (MessageBox.Show("是否要居中打印", "打印设置 - 页面居中", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
    22                 _dGVPrinter = new DataGridViewPrinter(_datagridview, MyPrintDocument, true, true, "OMH 详情", new System.Drawing.Font("宋体", 18, FontStyle.Bold, GraphicsUnit.Point), Color.Black, true);
    23             else
    24                 _dGVPrinter = new DataGridViewPrinter(_datagridview, MyPrintDocument, false, true, "OMH 详情", new System.Drawing.Font("宋体", 18, FontStyle.Bold, GraphicsUnit.Point), Color.Black, true);
    25 
    26             return true;
    27         }
    28 
    29         // 打印点击
    30         private void 打印ToolStripMenuItem_Click(object sender, EventArgs e)
    31         {
    32 
    33             foreach (Control c in this.Controls)
    34             {
    35                 if (c is DataGridView && c.Focused == true)
    36                 {
    37                     // Setting the style of the DataGridView control
    38                     (c as DataGridView).ColumnHeadersDefaultCellStyle.Font = new System.Drawing.Font("Tahoma", 9, FontStyle.Bold, GraphicsUnit.Point);
    39                     (c as DataGridView).ColumnHeadersDefaultCellStyle.BackColor = SystemColors.ControlDark;
    40                     (c as DataGridView).ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
    41                     (c as DataGridView).ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
    42                     (c as DataGridView).DefaultCellStyle.Font = new System.Drawing.Font("Tahoma", 8, FontStyle.Regular, GraphicsUnit.Point);
    43                     (c as DataGridView).DefaultCellStyle.BackColor = Color.Empty;
    44                     (c as DataGridView).AlternatingRowsDefaultCellStyle.BackColor = SystemColors.ControlLight;
    45                     (c as DataGridView).CellBorderStyle = DataGridViewCellBorderStyle.Single;
    46                     (c as DataGridView).GridColor = SystemColors.ControlDarkDark;
    47 
    48                     // Binding the DataGridViewControl to the DataSet generated above
    49                     //(c as DataGridView).DataSource = ds;
    50                     //(c as DataGridView).DataMember = "dt";
    51 
    52                     // Changing the last column alignment to be in the Right alignment            
    53                     (c as DataGridView).Columns[(c as DataGridView).Columns.Count - 1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
    54 
    55                     // Adjusting each column to be fit as the content of all its cells, including the header cell
    56                     (c as DataGridView).AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
    57 
    58 
    59                     if (SetupThePrinting(c as DataGridView))
    60                         MyPrintDocument.Print();
    61                 }
    62             }
    63         }
    64 
    65         // MyPrintDocument 打印页事件
    66         private void MyPrintDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
    67         {
    68             bool more = this._dGVPrinter.DrawDataGridView(e.Graphics);
    69             if (more == true)
    70                 e.HasMorePages = true;
    71         }

    打印预览的方法:

    Printing Priview
     1             foreach (Control c in this.Controls)
     2             {
     3                 if (c is DataGridView && c.Focused == true)
     4                 {
     5                     // Setting the style of the DataGridView control
     6                     (c as DataGridView).ColumnHeadersDefaultCellStyle.Font = new System.Drawing.Font("Tahoma", 9, FontStyle.Bold, GraphicsUnit.Point);
     7                     (c as DataGridView).ColumnHeadersDefaultCellStyle.BackColor = SystemColors.ControlDark;
     8                     (c as DataGridView).ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
     9                     (c as DataGridView).ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
    10                     (c as DataGridView).DefaultCellStyle.Font = new System.Drawing.Font("Tahoma", 8, FontStyle.Regular, GraphicsUnit.Point);
    11                     (c as DataGridView).DefaultCellStyle.BackColor = Color.Empty;
    12                     (c as DataGridView).AlternatingRowsDefaultCellStyle.BackColor = SystemColors.ControlLight;
    13                     (c as DataGridView).CellBorderStyle = DataGridViewCellBorderStyle.Single;
    14                     (c as DataGridView).GridColor = SystemColors.ControlDarkDark;
    15 
    16                     // Binding the DataGridViewControl to the DataSet generated above
    17                     //(c as DataGridView).DataSource = ds;
    18                     //(c as DataGridView).DataMember = "dt";
    19 
    20                     // Changing the last column alignment to be in the Right alignment            
    21                     (c as DataGridView).Columns[(c as DataGridView).Columns.Count - 1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
    22 
    23                     // Adjusting each column to be fit as the content of all its cells, including the header cell
    24                     (c as DataGridView).AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
    25 
    26                     if (SetupThePrinting(c as DataGridView))
    27                     {
    28                         PrintPreviewDialog MyPrintPreviewDialog = new PrintPreviewDialog();
    29                         MyPrintPreviewDialog.Document = this.MyPrintDocument;
    30                         MyPrintPreviewDialog.ShowDialog();
    31                     }
    32                 }
    33             }

    5、ZedGraph实现饼图、柱状图、折线图,这个貌似资料很多了,不贴代码了。

    只有一点,一种特殊的柱状图:每个BarItem上再分段的情况,实际是将柱状图的属性设定为Stack,然后分几段,就绑定几个数组。当时为了给客户显示这种,费心不少,后来才发现蛮简单的。

    6、C#中DateTime与String的转化。

    这个实在项目中遇到的比较头疼的一个问题,DateTime支持各种模式的输出,但是有些时候,计算时间的话,又不要从string转回DateTime,以前写了这样的一个类。现在看来,简直弱爆了。。。唉,纪念下吧,不过从string到DateTime,那些个模式串还是很烦人人,应该还会用到。

    DatetimeNString
     1     static class DatetimeNString
     2     {
     3         // 将表示时间的字符串,转化成DateTime类对象
     4         public static DateTime ToDateTime(string date)
     5         {
     6             string[] DateTimeList = {    
     7                 "yyyy-M-d tt hh:mm:ss",    
     8                 "yyyy-MM-dd tt hh:mm:ss",    
     9                 "yyyy-MM-dd HH:mm:ss",  
    10                 "yyyy-MM-dd HH:m:ss",  
    11                 "yyyy-MM-dd H:mm:ss",  
    12                 "yyyy-M-dd HH:mm:ss",
    13                 "yyyy-M-dd H:mm:ss",
    14                 "yyyy-M-dd HH:m:ss",
    15                 "yyyy-MM-d HH:mm:ss",
    16                 "yyyy-MM-d H:mm:ss",
    17                 "yyyy-MM-d HH:m:ss",
    18                 "yyyy-M-d HH:mm:ss",
    19                 "yyyy-M-d H:mm:ss",
    20                 "yyyy-M-d HH:m:ss",
    21                 "yyyy-MM-dd HH:mm",  
    22                 "yyyy-MM-dd H:mm",
    23                 "yyyy-MM-dd HH:m",
    24                 "yyyy-M-dd HH:mm",
    25                 "yyyy-M-dd H:mm",
    26                 "yyyy-M-dd HH:m",
    27                 "yyyy-MM-d HH:mm",
    28                 "yyyy-MM-d H:mm",
    29                 "yyyy-MM-d HH:m",
    30                 "yyyy-M-d HH:mm",  
    31                 "yyyy-M-d H:mm",
    32                 "yyyy-M-d HH:m",
    33                 "yyyy-M-d",    
    34                 "yyyy-MM-dd",
    35                 "HH:mm:ss",
    36                 "HH:mm;s",
    37                 "HH:m:ss",
    38                 "HH:m:s",
    39                 "H:mm:ss",
    40                 "H:mm;s",
    41                 "H:m:ss",
    42                 "H:m:s",
    43                 "HH:mm",
    44                 "HH:m",
    45                 "H:mm",
    46                 "H:m"
    47                 };
    48             DateTime dt = DateTime.ParseExact(date, DateTimeList, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AllowWhiteSpaces);
    49             return dt;
    50         }
    51 
    52         // 从DateTime对象中抽取日期
    53         public static string GetDate(DateTime datetime)
    54         {
    55             string date = datetime.Year + "-" + datetime.Month + "-" + datetime.Day;
    56             return date;
    57         }
    58 
    59         // 从DateTime对象中抽取时间
    60         public static string GetTime(DateTime datetime)
    61         {
    62             string time = datetime.Hour + ":" + datetime.Minute + ":" + datetime.Second;
    63             return time;
    64         }
    65 
    66         public static int TimeCompare(string start, string end)
    67         {
    68             return DateTime.Compare(DatetimeNString.ToDateTime(start), DatetimeNString.ToDateTime(end));
    69         }
    70     }

    写着写着天亮了,就这些吧。

    虽然,曾经费心苦熬出来的代码,现在看起来多少有些naive,但是,人总是这样吧,在不断的自我肯定中成长,在不断的自我否定中再进一步。

  • 相关阅读:
    APPlication,Session和Cookie的区别
    C# 中的Request对象的应用
    从字符串里提取一个列表(数组)
    UDP:用户数据报协议
    反射
    网络编程
    多线程
    final,finally和finalize的区别
    集合
    StringBuffer
  • 原文地址:https://www.cnblogs.com/YFYkuner/p/2592925.html
Copyright © 2020-2023  润新知