最近有个需求,是需要用WinForm打印表格,打印机是针式打印机,纸张则为发票联式的纸张(一联大小大概20cm*10cm),本文列举了两个打印方法,一个是用WinForm自带的打印类,另一个则是将表格输出到Excel后再打印。
首先先来看下页面的主要设计:
namespace WindowsApplication15
{
partial class Form1
{
///
/// 必需的设计器变量。
///
private System.ComponentModel.IContainer components = null;
///
/// 清理所有正在使用的资源。
///
/// 如果应释放托管资源,为 true;否则为 false。
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
///
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
///
private void InitializeComponent()
{
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle4 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle5 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle6 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle7 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle8 = new System.Windows.Forms.DataGridViewCellStyle();
this.panel1 = new System.Windows.Forms.Panel();
this.button3 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button1 = new System.Windows.Forms.Button();
this.printDocument1 = new System.Drawing.Printing.PrintDocument();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.panel2 = new System.Windows.Forms.Panel();
this.pageSetupDialog1 = new System.Windows.Forms.PageSetupDialog();
this.printDialog1 = new System.Windows.Forms.PrintDialog();
this.printPreviewDialog1 = new System.Windows.Forms.PrintPreviewDialog();
this.button4 = new System.Windows.Forms.Button();
this.rowMergeView1 = new RowMergeView();
this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Column2 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Column3 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Column4 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Column5 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Column6 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Column7 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.panel1.SuspendLayout();
this.panel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.rowMergeView1)).BeginInit();
this.SuspendLayout();
//
// panel1
//
this.panel1.Controls.Add(this.button4);
this.panel1.Controls.Add(this.button3);
this.panel1.Controls.Add(this.button2);
this.panel1.Controls.Add(this.button1);
this.panel1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.panel1.Location = new System.Drawing.Point(0, 386);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(751, 34);
this.panel1.TabIndex = 0;
//
// button3
//
this.button3.Location = new System.Drawing.Point(243, 4);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(75, 23);
this.button3.TabIndex = 2;
this.button3.Text = "打印预览";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(126, 4);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 1;
this.button2.Text = "打印设置";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// button1
//
this.button1.Anchor = System.Windows.Forms.AnchorStyles.None;
this.button1.Location = new System.Drawing.Point(12, 5);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "打印";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// printDocument1
//
this.printDocument1.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printDocument1_PrintPage);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("宋体", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.label1.Location = new System.Drawing.Point(201, 14);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(309, 19);
this.label1.TabIndex = 2;
this.label1.Text = "膳食服务中心新院网络订餐配送单";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 48);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(41, 12);
this.label2.TabIndex = 3;
this.label2.Text = "日期:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(12, 64);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(65, 12);
this.label3.TabIndex = 4;
this.label3.Text = "套餐类型:";
//
// panel2
//
this.panel2.Controls.Add(this.label3);
this.panel2.Controls.Add(this.label2);
this.panel2.Controls.Add(this.label1);
this.panel2.Controls.Add(this.rowMergeView1);
this.panel2.Location = new System.Drawing.Point(0, 12);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(740, 374);
this.panel2.TabIndex = 5;
//
// printDialog1
//
this.printDialog1.UseEXDialog = true;
//
// printPreviewDialog1
//
this.printPreviewDialog1.AutoScrollMargin = new System.Drawing.Size(0, 0);
this.printPreviewDialog1.AutoScrollMinSize = new System.Drawing.Size(0, 0);
this.printPreviewDialog1.ClientSize = new System.Drawing.Size(400, 300);
this.printPreviewDialog1.Enabled = true;
this.printPreviewDialog1.Icon = ((System.Drawing.Icon)(resources.GetObject("printPreviewDialog1.Icon")));
this.printPreviewDialog1.Name = "printPreviewDialog1";
this.printPreviewDialog1.Visible = false;
//
// button4
//
this.button4.Location = new System.Drawing.Point(355, 3);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(75, 23);
this.button4.TabIndex = 3;
this.button4.Text = "导出";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.button4_Click);
//
// rowMergeView1
//
this.rowMergeView1.AllowUserToAddRows = false;
this.rowMergeView1.AllowUserToDeleteRows = false;
this.rowMergeView1.BackgroundColor = System.Drawing.Color.White;
dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control;
dataGridViewCellStyle1.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.rowMergeView1.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
this.rowMergeView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.rowMergeView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.Column1,
this.Column2,
this.Column3,
this.Column4,
this.Column5,
this.Column6,
this.Column7});
this.rowMergeView1.Location = new System.Drawing.Point(14, 95);
this.rowMergeView1.MergeColumnHeaderBackColor = System.Drawing.SystemColors.Control;
this.rowMergeView1.MergeColumnNames = ((System.Collections.Generic.List<string>)(resources.GetObject("rowMergeView1.MergeColumnNames")));
this.rowMergeView1.Name = "rowMergeView1";
this.rowMergeView1.ReadOnly = true;
this.rowMergeView1.RowTemplate.Height = 23;
this.rowMergeView1.Size = new System.Drawing.Size(713, 242);
this.rowMergeView1.TabIndex = 1;
this.rowMergeView1.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.rowMergeView1_CellContentClick);
//
// Column1
//
this.Column1.DataPropertyName = "1";
dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
this.Column1.DefaultCellStyle = dataGridViewCellStyle2;
this.Column1.HeaderText = "地址";
this.Column1.Name = "Column1";
this.Column1.ReadOnly = true;
this.Column1.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
this.Column1.Width = 70;
//
// Column2
//
this.Column2.DataPropertyName = "2";
dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
this.Column2.DefaultCellStyle = dataGridViewCellStyle3;
this.Column2.HeaderText = "套餐名称";
this.Column2.Name = "Column2";
this.Column2.ReadOnly = true;
this.Column2.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
this.Column2.Width = 120;
//
// Column3
//
this.Column3.DataPropertyName = "3";
dataGridViewCellStyle4.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
this.Column3.DefaultCellStyle = dataGridViewCellStyle4;
this.Column3.HeaderText = "数量";
this.Column3.Name = "Column3";
this.Column3.ReadOnly = true;
this.Column3.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
this.Column3.Width = 60;
//
// Column4
//
this.Column4.DataPropertyName = "4";
dataGridViewCellStyle5.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
this.Column4.DefaultCellStyle = dataGridViewCellStyle5;
this.Column4.HeaderText = "订餐人员";
this.Column4.Name = "Column4";
this.Column4.ReadOnly = true;
this.Column4.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
this.Column4.Width = 90;
//
// Column5
//
this.Column5.DataPropertyName = "5";
dataGridViewCellStyle6.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
this.Column5.DefaultCellStyle = dataGridViewCellStyle6;
this.Column5.HeaderText = "联系电话";
this.Column5.Name = "Column5";
this.Column5.ReadOnly = true;
this.Column5.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
this.Column5.Width = 90;
//
// Column6
//
this.Column6.DataPropertyName = "6";
dataGridViewCellStyle7.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
this.Column6.DefaultCellStyle = dataGridViewCellStyle7;
this.Column6.HeaderText = "份数汇总";
this.Column6.Name = "Column6";
this.Column6.ReadOnly = true;
this.Column6.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
this.Column6.Width = 180;
//
// Column7
//
this.Column7.DataPropertyName = "7";
dataGridViewCellStyle8.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
this.Column7.DefaultCellStyle = dataGridViewCellStyle8;
this.Column7.HeaderText = "交接签名";
this.Column7.Name = "Column7";
this.Column7.ReadOnly = true;
this.Column7.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(751, 420);
this.Controls.Add(this.panel2);
this.Controls.Add(this.panel1);
this.Name = "Form1";
this.Text = "Form1";
this.panel1.ResumeLayout(false);
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.rowMergeView1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Button button1;
private System.Drawing.Printing.PrintDocument printDocument1;
private System.Windows.Forms.Label label1;
private RowMergeView rowMergeView1;
private System.Windows.Forms.DataGridViewTextBoxColumn Column1;
private System.Windows.Forms.DataGridViewTextBoxColumn Column2;
private System.Windows.Forms.DataGridViewTextBoxColumn Column3;
private System.Windows.Forms.DataGridViewTextBoxColumn Column4;
private System.Windows.Forms.DataGridViewTextBoxColumn Column5;
private System.Windows.Forms.DataGridViewTextBoxColumn Column6;
private System.Windows.Forms.DataGridViewTextBoxColumn Column7;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.PageSetupDialog pageSetupDialog1;
private System.Windows.Forms.PrintDialog printDialog1;
private System.Windows.Forms.PrintPreviewDialog printPreviewDialog1;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button4;
}
}
这里用Bitmap直接将页面打印出来,如果用网上常见的DataGridView打印类,上面的Label则不会被打印出来
//打印
private void button1_Click(object sender, EventArgs e) {
if (this.printDialog1.ShowDialog() == DialogResult.OK) {
this.printDocument1.Print();
}
}
//打印设置
private void button2_Click(object sender, EventArgs e) {
this.pageSetupDialog1.ShowDialog();
}
//打印预览
private void button3_Click(object sender, EventArgs e) {
this.printPreviewDialog1.ShowDialog();
}
//打印容器设置
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e) {
Bitmap _NewBitmap = new Bitmap(panel2.Width - 2, panel2.Height - 20);
panel2.DrawToBitmap(_NewBitmap, new Rectangle(0, 0, _NewBitmap.Width, _NewBitmap.Height));
e.Graphics.DrawImage(_NewBitmap, 0, 0, _NewBitmap.Width, _NewBitmap.Height);
}
this.rowMergeView1.MergeColumnNames.Add("Column1"); //合并Column1该列文本相同的单元格
this.rowMergeView1.MergeColumnNames.Add("Column6");
this.rowMergeView1.MergeColumnNames.Add("Column7");
//设置自动换行
this.rowMergeView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
//设置自动调整高度
this.rowMergeView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
//禁止最左边的空列头显示
this.rowMergeView1.RowHeadersVisible = false;
这里先不用数据库导入,先采用收到录入数据方式,来验证格式是否可用
DataTable dt = new DataTable();
dt.Columns.Add("1");
dt.Columns.Add("2");
dt.Columns.Add("3");
dt.Columns.Add("4");
dt.Columns.Add("5");
dt.Columns.Add("6");
dt.Columns.Add("7");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "香炸鸡腿套餐A", "1", "杨文静", "679357", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐B", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐C", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐D", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐E", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐F", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐G", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐H", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐I", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐J", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐K", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐L", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐M", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐N", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐O", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
this.rowMergeView1.DataSource = dt;
导出到Excel时可以同时设置Excel的格式,都在代码里,有注释
private void button4_Click(object sender, EventArgs e) {
string a = "D:" + "\\膳食服务中心新院网络订餐配送单.xls";
ExportExcels(a, rowMergeView1);
}
///
///
///
/// 文件路径
/// 控件DataGridView
private void ExportExcels(string fileName, RowMergeView myDGV) {
string saveFileName = "";
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xls";
saveDialog.Filter = "Excel文件|*.xls";
saveDialog.FileName = fileName;
saveDialog.ShowDialog();
saveFileName = saveDialog.FileName;
if (saveFileName.IndexOf(":") < 0) return; //被点了取消
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null) {
MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
return;
}
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1]; //取得sheet1
int rowCount = myDGV.Rows.Count; //行数
int columnCount = myDGV.Columns.Count; //列数
//写入标题
for (int i = 0; i < myDGV.ColumnCount; i++) {
worksheet.Cells[4, i + 1] = myDGV.Columns[i].HeaderText;
}
//写入数值
for (int r = 0; r < myDGV.RowCount; r++) {
for (int i = 0; i < myDGV.ColumnCount; i++) {
worksheet.Cells[r + 5, i + 1] = myDGV.Rows[r].Cells[i].Value;
}
Application.DoEvents();
}
//格式设置
worksheet.Columns.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; //所有单元格水平居中
worksheet.Columns.VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter; //垂直居中
worksheet.get_Range(worksheet.Cells[4, 1], worksheet.Cells[rowCount + 4, columnCount]).Borders.LineStyle = 1; //设置选定区域单元格边框,从第4行第1列开始绘制边框
//worksheet.Borders.LineStyle=1; //设置所有单元格边框的粗细
worksheet.Cells[1, 1] = "膳食服务中心新院网络订餐配送单"; //Excel单元格赋值
worksheet.Cells[2, 1] = "日期:"; //Excel单元格赋值
worksheet.get_Range("A2").HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft; //A2单元格水平靠左
worksheet.Cells[3, 1] = "套餐类型:"; //Excel单元格赋值
worksheet.get_Range("A3").HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft; //A3单元格水平靠左
worksheet.get_Range("A1", "G1").Merge(worksheet.get_Range("A1", "G1").MergeCells); //合并A1-G1的单元格
worksheet.get_Range("A2", "G2").Merge(worksheet.get_Range("A2", "G2").MergeCells); //合并A2-G2的单元格
worksheet.get_Range("A3", "G3").Merge(worksheet.get_Range("A3", "G3").MergeCells); //合并A3-G3的单元格
worksheet.get_Range("A1").ColumnWidth = 8.38; //设置A列宽
worksheet.get_Range("B1").ColumnWidth = 15.88; //设置B列宽
worksheet.get_Range("C1").ColumnWidth = 8.38; //设置C列宽
worksheet.get_Range("D1").ColumnWidth = 8.38; //设置D列宽
worksheet.get_Range("E1").ColumnWidth = 8.38; //设置E列宽
worksheet.get_Range("F1").ColumnWidth = 20.88; //设置F列宽
worksheet.get_Range("G1").ColumnWidth = 13; //设置G列宽
//合并选定区域单元格,从第5行第1列开始合并
worksheet.get_Range(worksheet.Cells[5, 1], worksheet.Cells[rowCount + 4, 1]).Merge(worksheet.get_Range(worksheet.Cells[5, 1], worksheet.Cells[rowCount + 4, 1]).MergeCells);
//合并选定区域单元格,从第5行第6列开始合并
worksheet.get_Range(worksheet.Cells[5, 6], worksheet.Cells[rowCount + 4, 6]).Merge(worksheet.get_Range(worksheet.Cells[5, 6], worksheet.Cells[rowCount + 4, 6]).MergeCells);
//合并选定区域单元格,从第5行第7列开始合并
worksheet.get_Range(worksheet.Cells[5, 7], worksheet.Cells[rowCount + 4, 7]).Merge(worksheet.get_Range(worksheet.Cells[5, 7], worksheet.Cells[rowCount + 4, 7]).MergeCells);
worksheet.Columns.EntireColumn.AutoFit(); //列宽自适应
worksheet.Rows.EntireRow.AutoFit(); //行高自适应
if (saveFileName != "") {
try {
workbook.Saved = true;
workbook.SaveCopyAs(saveFileName);
}
catch (Exception ex) {
MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
}
}
xlApp.Quit();
GC.Collect();//强行销毁
MessageBox.Show("文件: " + fileName + ".xls 保存成功", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication15 {
public partial class Form1 : Form {
public Form1()
{
InitializeComponent();
DataTable dt = new DataTable();
dt.Columns.Add("1");
dt.Columns.Add("2");
dt.Columns.Add("3");
dt.Columns.Add("4");
dt.Columns.Add("5");
dt.Columns.Add("6");
dt.Columns.Add("7");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "香炸鸡腿套餐A", "1", "杨文静", "679357", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐B", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐C", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐D", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐E", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐F", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐G", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐H", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐I", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐J", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐K", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐L", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐M", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐N", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
dt.Rows.Add("122病区" + "\r\n" + "护士台", "鱼香肉丝套餐O", "1", "刘林荣", "670327", "香炸鸡腿套餐C共1份;" + "\r\n" + "鱼香肉丝套餐A共1份;" + "\r\n" + "套餐总共份数2", "");
this.rowMergeView1.DataSource = dt;
//this.rowMergeView1.ColumnHeadersHeight = 40;
//this.rowMergeView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
this.rowMergeView1.MergeColumnNames.Add("Column1"); //合并Column1该列文本相同的单元格
this.rowMergeView1.MergeColumnNames.Add("Column6");
this.rowMergeView1.MergeColumnNames.Add("Column7");
//设置自动换行
this.rowMergeView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
//设置自动调整高度
this.rowMergeView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
//禁止最左边的空列头显示
this.rowMergeView1.RowHeadersVisible = false;
}
private void rowMergeView1_CellContentClick(object sender, DataGridViewCellEventArgs e) {
}
private void label1_Click(object sender, EventArgs e) {
}
private void panel1_Paint(object sender, PaintEventArgs e) {
}
//打印
private void button1_Click(object sender, EventArgs e) {
if (this.printDialog1.ShowDialog() == DialogResult.OK) {
this.printDocument1.Print();
}
}
//打印设置
private void button2_Click(object sender, EventArgs e) {
this.pageSetupDialog1.ShowDialog();
}
//打印预览
private void button3_Click(object sender, EventArgs e) {
this.printPreviewDialog1.ShowDialog();
}
//打印容器设置
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e) {
Bitmap _NewBitmap = new Bitmap(panel2.Width - 2, panel2.Height - 20);
panel2.DrawToBitmap(_NewBitmap, new Rectangle(0, 0, _NewBitmap.Width, _NewBitmap.Height));
e.Graphics.DrawImage(_NewBitmap, 0, 0, _NewBitmap.Width, _NewBitmap.Height);
}
private void button4_Click(object sender, EventArgs e) {
string a = "D:" + "\\膳食服务中心新院网络订餐配送单.xls";
ExportExcels(a, rowMergeView1);
}
///
///
///
/// 文件路径
/// 控件DataGridView
private void ExportExcels(string fileName, RowMergeView myDGV) {
string saveFileName = "";
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xls";
saveDialog.Filter = "Excel文件|*.xls";
saveDialog.FileName = fileName;
saveDialog.ShowDialog();
saveFileName = saveDialog.FileName;
if (saveFileName.IndexOf(":") < 0) return; //被点了取消
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null) {
MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
return;
}
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1]; //取得sheet1
int rowCount = myDGV.Rows.Count; //行数
int columnCount = myDGV.Columns.Count; //列数
//写入标题
for (int i = 0; i < myDGV.ColumnCount; i++) {
worksheet.Cells[4, i + 1] = myDGV.Columns[i].HeaderText;
}
//写入数值
for (int r = 0; r < myDGV.RowCount; r++) {
for (int i = 0; i < myDGV.ColumnCount; i++) {
worksheet.Cells[r + 5, i + 1] = myDGV.Rows[r].Cells[i].Value;
}
Application.DoEvents();
}
//格式设置
worksheet.Columns.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; //所有单元格水平居中
worksheet.Columns.VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter; //垂直居中
worksheet.get_Range(worksheet.Cells[4, 1], worksheet.Cells[rowCount + 4, columnCount]).Borders.LineStyle = 1; //设置选定区域单元格边框,从第4行第1列开始绘制边框
//worksheet.Borders.LineStyle=1; //设置所有单元格边框的粗细
worksheet.Cells[1, 1] = "膳食服务中心新院网络订餐配送单"; //Excel单元格赋值
worksheet.Cells[2, 1] = "日期:"; //Excel单元格赋值
worksheet.get_Range("A2").HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft; //A2单元格水平靠左
worksheet.Cells[3, 1] = "套餐类型:"; //Excel单元格赋值
worksheet.get_Range("A3").HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft; //A3单元格水平靠左
worksheet.get_Range("A1", "G1").Merge(worksheet.get_Range("A1", "G1").MergeCells); //合并A1-G1的单元格
worksheet.get_Range("A2", "G2").Merge(worksheet.get_Range("A2", "G2").MergeCells); //合并A2-G2的单元格
worksheet.get_Range("A3", "G3").Merge(worksheet.get_Range("A3", "G3").MergeCells); //合并A3-G3的单元格
worksheet.get_Range("A1").ColumnWidth = 8.38; //设置A列宽
worksheet.get_Range("B1").ColumnWidth = 15.88; //设置B列宽
worksheet.get_Range("C1").ColumnWidth = 8.38; //设置C列宽
worksheet.get_Range("D1").ColumnWidth = 8.38; //设置D列宽
worksheet.get_Range("E1").ColumnWidth = 8.38; //设置E列宽
worksheet.get_Range("F1").ColumnWidth = 20.88; //设置F列宽
worksheet.get_Range("G1").ColumnWidth = 13; //设置G列宽
//合并选定区域单元格,从第5行第1列开始合并
worksheet.get_Range(worksheet.Cells[5, 1], worksheet.Cells[rowCount + 4, 1]).Merge(worksheet.get_Range(worksheet.Cells[5, 1], worksheet.Cells[rowCount + 4, 1]).MergeCells);
//合并选定区域单元格,从第5行第6列开始合并
worksheet.get_Range(worksheet.Cells[5, 6], worksheet.Cells[rowCount + 4, 6]).Merge(worksheet.get_Range(worksheet.Cells[5, 6], worksheet.Cells[rowCount + 4, 6]).MergeCells);
//合并选定区域单元格,从第5行第7列开始合并
worksheet.get_Range(worksheet.Cells[5, 7], worksheet.Cells[rowCount + 4, 7]).Merge(worksheet.get_Range(worksheet.Cells[5, 7], worksheet.Cells[rowCount + 4, 7]).MergeCells);
worksheet.Columns.EntireColumn.AutoFit(); //列宽自适应
worksheet.Rows.EntireRow.AutoFit(); //行高自适应
if (saveFileName != "") {
try {
workbook.Saved = true;
workbook.SaveCopyAs(saveFileName);
}
catch (Exception ex) {
MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
}
}
xlApp.Quit();
GC.Collect();//强行销毁
MessageBox.Show("文件: " + fileName + ".xls 保存成功", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
也放一下大佬写的RowMergeView吧
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Design;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Reflection;
using System.Runtime.InteropServices;
///
/// DataGridView行合并.请对属性MergeColumnNames 赋值既可
///
public partial class RowMergeView : DataGridView
{
#region 构造函数
public RowMergeView()
{
InitializeComponent();
}
#endregion
#region 重写的事件
protected override void OnPaint(PaintEventArgs pe)
{
// TODO: 在此处添加自定义绘制代码
// 调用基类 OnPaint
base.OnPaint(pe);
}
protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e)
{
try
{
if (e.RowIndex > -1 && e.ColumnIndex > -1)
{
DrawCell(e);
}
else
{
//二维表头
if (e.RowIndex == -1)
{
if (SpanRows.ContainsKey(e.ColumnIndex)) //被合并的列
{
//画边框
Graphics g = e.Graphics;
e.Paint(e.CellBounds, DataGridViewPaintParts.Background | DataGridViewPaintParts.Border);
int left = e.CellBounds.Left, top = e.CellBounds.Top + 2,
right = e.CellBounds.Right, bottom = e.CellBounds.Bottom;
switch (SpanRows[e.ColumnIndex].Position)
{
case 1:
left += 2;
break;
case 2:
break;
case 3:
right -= 2;
break;
}
//画上半部分底色
g.FillRectangle(new SolidBrush(this._mergecolumnheaderbackcolor), left, top,
right - left, (bottom - top) / 2);
//画中线
g.DrawLine(new Pen(this.GridColor), left, (top + bottom) / 2,
right, (top + bottom) / 2);
//写小标题
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
g.DrawString(e.Value + "", e.CellStyle.Font, Brushes.Black,
new Rectangle(left, (top + bottom) / 2, right - left, (bottom - top) / 2), sf);
left = this.GetColumnDisplayRectangle(SpanRows[e.ColumnIndex].Left, true).Left - 2;
if (left < 0) left = this.GetCellDisplayRectangle(-1, -1, true).Width;
right = this.GetColumnDisplayRectangle(SpanRows[e.ColumnIndex].Right, true).Right - 2;
if (right < 0) right = this.Width;
g.DrawString(SpanRows[e.ColumnIndex].Text, e.CellStyle.Font, Brushes.Black,
new Rectangle(left, top, right - left, (bottom - top) / 2), sf);
e.Handled = true;
}
}
}
base.OnCellPainting(e);
}
catch
{
}
}
protected override void OnCellClick(DataGridViewCellEventArgs e)
{
base.OnCellClick(e);
}
#endregion
#region 自定义方法
///
/// 画单元格
///
///
private void DrawCell(DataGridViewCellPaintingEventArgs e)
{
if (e.CellStyle.Alignment == DataGridViewContentAlignment.NotSet)
{
e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
}
Brush gridBrush = new SolidBrush(this.GridColor);
SolidBrush backBrush = new SolidBrush(e.CellStyle.BackColor);
SolidBrush fontBrush = new SolidBrush(e.CellStyle.ForeColor);
int cellwidth;
//上面相同的行数
int UpRows = 0;
//下面相同的行数
int DownRows = 0;
//总行数
int count = 0;
if (this.MergeColumnNames.Contains(this.Columns[e.ColumnIndex].Name) && e.RowIndex != -1)
{
cellwidth = e.CellBounds.Width;
Pen gridLinePen = new Pen(gridBrush);
string curValue = e.Value == null ? "" : e.Value.ToString().Trim();
string curSelected = this.CurrentRow.Cells[e.ColumnIndex].Value == null ? "" : this.CurrentRow.Cells[e.ColumnIndex].Value.ToString().Trim();
if (!string.IsNullOrEmpty(curValue))
{
#region 获取下面的行数
for (int i = e.RowIndex; i < this.Rows.Count; i++)
{
if (this.Rows[i].Cells[e.ColumnIndex].Value.ToString().Equals(curValue))
{
//this.Rows[i].Cells[e.ColumnIndex].Selected = this.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected;
DownRows++;
if (e.RowIndex != i)
{
cellwidth = cellwidth < this.Rows[i].Cells[e.ColumnIndex].Size.Width ? cellwidth : this.Rows[i].Cells[e.ColumnIndex].Size.Width;
}
}
else
{
break;
}
}
#endregion
#region 获取上面的行数
for (int i = e.RowIndex; i >= 0; i--)
{
if (this.Rows[i].Cells[e.ColumnIndex].Value.ToString().Equals(curValue))
{
//this.Rows[i].Cells[e.ColumnIndex].Selected = this.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected;
UpRows++;
if (e.RowIndex != i)
{
cellwidth = cellwidth < this.Rows[i].Cells[e.ColumnIndex].Size.Width ? cellwidth : this.Rows[i].Cells[e.ColumnIndex].Size.Width;
}
}
else
{
break;
}
}
#endregion
count = DownRows + UpRows - 1;
if (count < 2)
{
return;
}
}
if (this.Rows[e.RowIndex].Selected)
{
backBrush.Color = e.CellStyle.SelectionBackColor;
fontBrush.Color = e.CellStyle.SelectionForeColor;
}
//以背景色填充
e.Graphics.FillRectangle(backBrush, e.CellBounds);
//画字符串
PaintingFont(e, cellwidth, UpRows, DownRows, count);
if (DownRows == 1)
{
e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
count = 0;
}
// 画右边线
e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom);
e.Handled = true;
}
}
///
/// 画字符串
///
///
///
///
///
///
private void PaintingFont(System.Windows.Forms.DataGridViewCellPaintingEventArgs e, int cellwidth, int UpRows, int DownRows, int count)
{
SolidBrush fontBrush = new SolidBrush(e.CellStyle.ForeColor);
int fontheight = (int)e.Graphics.MeasureString(e.Value.ToString(), e.CellStyle.Font).Height;
int fontwidth = (int)e.Graphics.MeasureString(e.Value.ToString(), e.CellStyle.Font).Width;
int cellheight = e.CellBounds.Height;
if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomCenter)
{
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y + cellheight * DownRows - fontheight);
}
else if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomLeft)
{
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y + cellheight * DownRows - fontheight);
}
else if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomRight)
{
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y + cellheight * DownRows - fontheight);
}
else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleCenter)
{
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
}
else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleLeft)
{
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
}
else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleRight)
{
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
}
else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopCenter)
{
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1));
}
else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopLeft)
{
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y - cellheight * (UpRows - 1));
}
else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopRight)
{
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y - cellheight * (UpRows - 1));
}
else
{
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
}
}
#endregion
#region 属性
///
/// 设置或获取合并列的集合
///
[MergableProperty(false)]
[Editor("System.Windows.Forms.Design.ListControlStringCollectionEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
[DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Visible)]
[Localizable(true)]
[Description("设置或获取合并列的集合"), Browsable(true), Category("单元格合并")]
public List<string> MergeColumnNames
{
get
{
return _mergecolumnname;
}
set
{
_mergecolumnname = value;
}
}
private List<string> _mergecolumnname = new List<string>();
#endregion
#region 二维表头
private struct SpanInfo //表头信息
{
public SpanInfo(string Text, int Position, int Left, int Right)
{
this.Text = Text;
this.Position = Position;
this.Left = Left;
this.Right = Right;
}
public string Text; //列主标题
public int Position; //位置,1:左,2中,3右
public int Left; //对应左行
public int Right; //对应右行
}
private Dictionary<int, SpanInfo> SpanRows = new Dictionary<int, SpanInfo>();//需要2维表头的列
///
/// 合并列
///
/// 列的索引
/// 需要合并的列数
/// 合并列后的文本
public void AddSpanHeader(int ColIndex, int ColCount, string Text)
{
if (ColCount < 2)
{
throw new Exception("行宽应大于等于2,合并1列无意义。");
}
//将这些列加入列表
int Right = ColIndex + ColCount - 1; //同一大标题下的最后一列的索引
SpanRows[ColIndex] = new SpanInfo(Text, 1, ColIndex, Right); //添加标题下的最左列
SpanRows[Right] = new SpanInfo(Text, 3, ColIndex, Right); //添加该标题下的最右列
for (int i = ColIndex + 1; i < Right; i++) //中间的列
{
SpanRows[i] = new SpanInfo(Text, 2, ColIndex, Right);
}
}
///
/// 清除合并的列
///
public void ClearSpanInfo()
{
SpanRows.Clear();
//ReDrawHead();
}
private void DataGridViewEx_Scroll(object sender, ScrollEventArgs e)
{
if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll)// && e.Type == ScrollEventType.EndScroll)
{
timer1.Enabled = false; timer1.Enabled = true;
}
}
//刷新显示表头
public void ReDrawHead()
{
foreach (int si in SpanRows.Keys)
{
this.Invalidate(this.GetCellDisplayRectangle(si, -1, true));
}
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Enabled = false;
ReDrawHead();
}
///
/// 二维表头的背景颜色
///
[Description("二维表头的背景颜色"), Browsable(true), Category("二维表头")]
public Color MergeColumnHeaderBackColor
{
get {
return this._mergecolumnheaderbackcolor; }
set {
this._mergecolumnheaderbackcolor = value; }
}
private Color _mergecolumnheaderbackcolor = System.Drawing.SystemColors.Control;
#endregion
private void timer1_Tick_1(object sender, EventArgs e) {
}
}
百度云盘链接,失效请留言 提取码:9k8i
CSDN下载链接,失效请留言