对DataGridView控件的扩展开发

首先在项目中引用
System.Drawing.Design;
System.Windows.Forms;
项目A:
说明:项目A要引用项目B


using System.Drawing;
using System.Drawing.Design;
using System.Windows.Forms;
namespace HR.Control
{
public class DataGridViewC:DataGridView
{
/// <summary>
/// 功能id
/// </summary>
public int formId;

/// <summary>
/// 列排序
/// </summary>
public bool hRColumnSort = true;

#region"定义右键菜单选项"
internal System.Windows.Forms.ContextMenuStrip contextMenu = null;
internal System.Windows.Forms.ToolStripMenuItem 输出到Excel文件ToolStripMenuItem;
internal System.Windows.Forms.ToolStripSeparator ToolStripMenuItem1;
internal System.Windows.Forms.ToolStripMenuItem 升序ToolStripMenuItem;
internal System.Windows.Forms.ToolStripMenuItem 降序ToolStripMenuItem;
internal System.Windows.Forms.ToolStripSeparator ToolStripMenuItem2;
internal System.Windows.Forms.ToolStripMenuItem 复制ToolStripMenuItem;
internal System.Windows.Forms.ToolStripMenuItem 复制到ToolStripMenuItem;
internal System.Windows.Forms.ToolStripMenuItem MicrosoftWordToolStripMenuItem;
internal System.Windows.Forms.ToolStripMenuItem MicrosoftExcelToolStripMenuItem;
internal System.Windows.Forms.ToolStripMenuItem 另存为Excel文件;
internal System.Windows.Forms.ToolStripSeparator ToolStripMenuItem3;
internal System.Windows.Forms.ToolStripMenuItem 自动列宽ToolStripMenuItem;
internal System.Windows.Forms.ToolStripSeparator ToolStripMenuItem4;
internal System.Windows.Forms.ToolStripMenuItem 检索ToolStripMenuItem;
internal System.Windows.Forms.ToolStripMenuItem 锁定到此行ToolStripMenuItem;
internal System.Windows.Forms.ToolStripMenuItem 锁定到此列ToolStripMenuItem;
#endregion

/// <summary>
/// 初始化DataGridViewC类的新实例。
/// </summary>
/// <remarks></remarks>
public DataGridViewC()
{

this.GridColor = Color.Green;
this.BackgroundColor = Color.Linen;
this.VirtualMode = true;

this.AllowUserToAddRows = false;
this.AllowUserToDeleteRows = false;
this.AllowUserToOrderColumns = true;
this.AllowUserToResizeColumns = true;
this.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
this.ReadOnly = true;
this.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
this.DataSource = null;
this.DataSourceChanged+=new EventHandler(DataGridViewDataSourceChanged);
AddContextMenu();
this.ContextMenuStrip = this.contextMenu;
GC.Collect();

}

/// <summary>
/// 添加右键菜单项
/// </summary>
private void AddContextMenu()
{
this.contextMenu = new ContextMenuStrip();
输出到Excel文件ToolStripMenuItem=new ToolStripMenuItem();
ToolStripMenuItem1=new ToolStripSeparator();
升序ToolStripMenuItem = new ToolStripMenuItem();
降序ToolStripMenuItem=new ToolStripMenuItem();
ToolStripMenuItem2=new ToolStripSeparator();
复制ToolStripMenuItem=new ToolStripMenuItem();
复制到ToolStripMenuItem=new ToolStripMenuItem();
MicrosoftWordToolStripMenuItem=new ToolStripMenuItem();
MicrosoftExcelToolStripMenuItem=new ToolStripMenuItem();
另存为Excel文件=new ToolStripMenuItem();
ToolStripMenuItem3=new ToolStripSeparator();
自动列宽ToolStripMenuItem=new ToolStripMenuItem();
ToolStripMenuItem4=new ToolStripSeparator();
检索ToolStripMenuItem=new ToolStripMenuItem();
锁定到此行ToolStripMenuItem=new ToolStripMenuItem();
锁定到此列ToolStripMenuItem = new ToolStripMenuItem();


输出到Excel文件ToolStripMenuItem.Text = "输出到Excel文件";
输出到Excel文件ToolStripMenuItem.Name = "输出到Excel文件ToolStripMenuItem";

ToolStripMenuItem1.Name = "ToolStripMenuItem1";

升序ToolStripMenuItem.Text = "↑升序";
升序ToolStripMenuItem.Name = "升序ToolStripMenuItem";

降序ToolStripMenuItem.Text = "↓降序";
降序ToolStripMenuItem.Name = "降序ToolStripMenuItem";

ToolStripMenuItem2.Name = "ToolStripMenuItem2";

复制ToolStripMenuItem.Name = "复制ToolStripMenuItem";
复制ToolStripMenuItem.Text = "复制(&C)";
复制ToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.P;

复制到ToolStripMenuItem.Name = "复制到ToolStripMenuItem";
复制到ToolStripMenuItem.Text = "复制到...";
复制到ToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { this.MicrosoftWordToolStripMenuItem, this.MicrosoftExcelToolStripMenuItem });

MicrosoftExcelToolStripMenuItem.Name = "MicrosoftWordToolStripMenuItem";
MicrosoftExcelToolStripMenuItem.Text = "Microsoft.Excel";
MicrosoftWordToolStripMenuItem.Name = "MicrosoftWordToolStripMenuItem";
MicrosoftWordToolStripMenuItem.Text = "Microsoft.Word";

另存为Excel文件.Name = "另存为Excel文件";
另存为Excel文件.Text = "另存为Excel文件";

ToolStripMenuItem3.Name = "ToolStripMenuItem3";

自动列宽ToolStripMenuItem.Name = "自动列宽ToolStripMenuItem";
自动列宽ToolStripMenuItem.Text = "自动列宽";

ToolStripMenuItem4.Name = "ToolStripMenuItem4";

检索ToolStripMenuItem.Name = "检索ToolStripMenuItem";
检索ToolStripMenuItem.Text = "检索";

锁定到此行ToolStripMenuItem.Name = "锁定到此行ToolStripMenuItem";
锁定到此行ToolStripMenuItem.Text = "锁定到此行";


锁定到此列ToolStripMenuItem.Name = "锁定到此列ToolStripMenuItem";
锁定到此列ToolStripMenuItem.Text = "锁定到此列";

this.contextMenu.Items.AddRange(new ToolStripItem[]{
this.输出到Excel文件ToolStripMenuItem,this.另存为Excel文件,this.ToolStripMenuItem1,this.复制ToolStripMenuItem,
this.复制到ToolStripMenuItem,this.ToolStripMenuItem2,this.检索ToolStripMenuItem,this.自动列宽ToolStripMenuItem,this.ToolStripMenuItem4,
this.升序ToolStripMenuItem,this.降序ToolStripMenuItem,this.ToolStripMenuItem3,this.锁定到此行ToolStripMenuItem,this.锁定到此列ToolStripMenuItem});

this.contextMenu.Opening += new System.ComponentModel.CancelEventHandler(contextMenu_Opening);

this.另存为Excel文件.Click += new EventHandler(另存为Excel文件_Click);
this.输出到Excel文件ToolStripMenuItem.Click += new EventHandler(输出到Excel文件ToolStripMenuItem_Click);
this.升序ToolStripMenuItem.Click += new EventHandler(AscendOrderSort);
this.降序ToolStripMenuItem.Click += new EventHandler(DescOrderSort);
this.复制ToolStripMenuItem.Click += new EventHandler(this.CopyData);
this.MicrosoftExcelToolStripMenuItem.Click += new EventHandler(MicrosoftExcelToolStripMenuItem_Click);
this.MicrosoftWordToolStripMenuItem.Click += new EventHandler(MicrosoftWordToolStripMenuItem_Click);
this.自动列宽ToolStripMenuItem.Click += new EventHandler(AutoSizeColumn);
this.锁定到此行ToolStripMenuItem.Click += new EventHandler(LockCurrR);
this.锁定到此列ToolStripMenuItem.Click += new EventHandler(LockCurrC);
this.检索ToolStripMenuItem.Click += new EventHandler(SearchGrid);


}

/// <summary>
/// 检索操作
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks></remarks>
void SearchGrid(object sender, EventArgs e)
{
HR.Control.SearchSelect SS = new SearchSelect();
SS.FindAndSelect(this, SearchSelect.FindOption.FindText);
}

/// <summary>
/// 锁定当前列
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks></remarks>
void LockCurrC(object sender, EventArgs e)
{
try
{
if (!this.锁定到此列ToolStripMenuItem.Checked)
{
this.锁定到此列ToolStripMenuItem.Checked = true;
this.Columns[this.CurrentCell.ColumnIndex].Frozen = true;
}
else
{
this.锁定到此列ToolStripMenuItem.Checked = false;
this.Columns[0].Frozen = false;

}
}
catch
{

}
}

/// <summary>
/// 锁定当前行
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks></remarks>
void LockCurrR(object sender, EventArgs e)
{
try
{
if (!this.锁定到此行ToolStripMenuItem.Checked)
{
this.Rows[CurrentCell.RowIndex].Frozen = true;
this.锁定到此行ToolStripMenuItem.Checked = true;
}
else
{
this.Rows[0].Frozen = false;
this.锁定到此行ToolStripMenuItem.Checked = false;

}
}
catch
{

}
}

/// <summary>
/// 自动列宽设置
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks></remarks>
void AutoSizeColumn(object sender, EventArgs e)
{
if (!this.自动列宽ToolStripMenuItem.Checked)
{
this.Cursor = Cursors.WaitCursor;
this.自动列宽ToolStripMenuItem.Checked = true;
this.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
}
else
{
this.自动列宽ToolStripMenuItem.Checked = false;
this.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
}
this.Cursor = Cursors.Default;
}


/// <summary>
/// 复制选中的数据到Word
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void MicrosoftWordToolStripMenuItem_Click(object sender, EventArgs e)
{
//引用项目B组件
HR.Control.DataGridViewOperation.Operate.OutputOperate OO = new HR.Control.DataGridViewOperation.Operate.OutputOperate();
OO.OutputFileToWord(this, "财务审计系统");
}

/// <summary>
/// 复制选中的数据到Excel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void MicrosoftExcelToolStripMenuItem_Click(object sender, EventArgs e)
{
// throw new NotImplementedException();
HR.Control.DataGridViewOperation.Operate.OutputOperate outDgv = new HR.Control.DataGridViewOperation.Operate.OutputOperate();
outDgv.CopyToExcel(this, "DataGridView选中单元格导入到Excel练习");
}

void 输出到Excel文件ToolStripMenuItem_Click(object sender, EventArgs e)
{
HR.Control.DataGridViewOperation.Operate.OutputOperate OO = new HR.Control.DataGridViewOperation.Operate.OutputOperate();
OO.OutputFileToExcel(this, System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\temp.xls", true);
}

void 另存为Excel文件_Click(object sender, EventArgs e)
{
if (this.RowCount==0||this.ColumnCount==0)
{
return;
}

SaveFileDialog SFD = new SaveFileDialog();
SFD.Filter = "Microsoft Excel电子文档(*.xls)|*.xls";
if (SFD.ShowDialog()==DialogResult.OK)
{
this.Cursor = Cursors.WaitCursor;
//引用项目B组件 HR.Control.DataGridViewOperation.Operate.OutputOperate OO = new HR.Control.DataGridViewOperation.Operate.OutputOperate();
OO.OutputFileToExcel(this, SFD.FileName, false);
GC.Collect();
this.Cursor = Cursors.Default;
}
}


/// <summary>
/// 复制选中单元格的数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void CopyData(object sender, EventArgs e)
{
if (this.Rows.Count==0 || this.Columns.Count==0)
{
return;
}
this.Focus();
int i = this.GetCellCount(DataGridViewElementStates.Selected);
if (i>0)
{
Clipboard.SetDataObject(this.GetClipboardContent());
}

}

/// <summary>
/// 降序操作
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks></remarks>
void DescOrderSort(object sender, EventArgs e)
{
if (this.Rows.Count==0 || this.Columns.Count==0)
{
return;
}
try
{
this.Cursor = Cursors.WaitCursor;
this.Sort(this.CurrentCell.OwningColumn, System.ComponentModel.ListSortDirection.Descending);
this.Cursor = Cursors.Default;
}
catch
{

}
}

/// <summary>
///升序操作
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks></remarks>
void AscendOrderSort(object sender, EventArgs e)
{
if (this.Rows.Count==0 || this.Columns.Count==0 )
{
return;
}
try
{
this.Cursor = Cursors.WaitCursor;
this.Sort(CurrentCell.OwningColumn, System.ComponentModel.ListSortDirection.Ascending);
this.Cursor = Cursors.Default;
}
catch
{

}
}


/// <summary>
/// 右键菜单弹出时所做的操作
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.ComponentModel.CancelEventArgs"/> instance containing the event data.</param>
/// <remarks></remarks>
void contextMenu_Opening(object sender, System.ComponentModel.CancelEventArgs e)
{
try
{
if (this.AutoSizeColumnsMode == DataGridViewAutoSizeColumnsMode.AllCells)
{
this.自动列宽ToolStripMenuItem.Checked = true;
}
else
{
this.自动列宽ToolStripMenuItem.Checked = false;
}

if (this.SelectedCells.Count == 1)
{
this.锁定到此行ToolStripMenuItem.Enabled = true;
this.锁定到此列ToolStripMenuItem.Enabled = true;

if (!this.Rows[this.CurrentCell.RowIndex].Frozen)
{
this.锁定到此行ToolStripMenuItem.Enabled = true;
}
else
{
this.锁定到此行ToolStripMenuItem.Enabled = true;
}

if (!this.Columns[this.CurrentCell.ColumnIndex].Frozen)
{
this.锁定到此列ToolStripMenuItem.Enabled = true;
}
else
{
this.锁定到此列ToolStripMenuItem.Enabled = false;
}
}
else
{
this.锁定到此行ToolStripMenuItem.Enabled = false;
this.锁定到此列ToolStripMenuItem.Enabled = false;
}
}
catch
{

}
}


/// <summary>
/// 填充数据表控件时,设置各列是否允许排序
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks></remarks>
private void DataGridViewDataSourceChanged(object sender, EventArgs e)
{
try
{
for (int i = 0; i < this.Columns.Count; i++)
{
if (!this.HRColumnSort)
{
this.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
}
if (this.Columns[i].ValueType.ToString().ToLower() == "system.decimal")
{
this.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
}
if (this.Columns[i].ValueType.ToString().ToLower() == "int32")
{
this.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
}
if (this.Columns[i].ValueType.ToString().IndexOf("方向") > -1)
{
this.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; ;
}
}
}
catch
{

}

}

#region DataGridView自定义属性
public int FormId
{
get { return formId; }
set { formId = value; }
}
public bool HRColumnSort
{
get
{
return hRColumnSort;
}
set
{
hRColumnSort = value;
if (hRColumnSort)
{
this.降序ToolStripMenuItem.Enabled = true;
this.升序ToolStripMenuItem.Enabled = true;
try
{
for (int i = 0; i < this.ColumnCount; i++)
{
this.Columns[i].SortMode = DataGridViewColumnSortMode.Automatic;
}
}
catch
{

}
}
else
{

this.降序ToolStripMenuItem.Enabled = false;
this.升序ToolStripMenuItem.Enabled = false;
try
{
for (int i = 0; i < this.ColumnCount; i++)
{
this.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
}
}
catch
{

}

}
}
}
#endregion

}
}


项目B
项目B在外面需要引用
Microsoft.Office.Interop.Excel
Microsoft.Office.Interop.Word
DataGridView导出Excel、Word、鼠标选定求和等扩展功能。

using System.Runtime.InteropServices;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Word;
namespace HR.Control.DataGridViewOperation
{
public class Operate
{
/// <summary>
/// DataGridView输出类操作
/// </summary>
public class OutputOperate
{
//杀Excel后台进程
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int Pid);

/// <summary>
/// DataGridView控件选中数据保存到Excel
/// </summary>
/// <param name="ExportDgv"></param>
/// <param name="DgvTitle"></param>
/// <returns></returns>
public bool CopyToExcel(DataGridView ExportDgv, string DgvTitle)
{
try
{
if (ExportDgv == null)
{
return false;
}

if (ExportDgv.Columns.Count == 0 || ExportDgv.Rows.Count == 0)
{
return false;
}

//Excel2003最大行是65535 ,最大列是255
//Excel2007最大行是1048576,最大列是16384
//if (ExportDgv.RowCount > 65536 || ExportDgv.ColumnCount > 256)
//{
// return false;
//}

ExportDgv.Focus();

//复制数据到Clipboard
int I = ExportDgv.GetCellCount(DataGridViewElementStates.Selected);
if (I > 0)
{
Clipboard.SetDataObject(ExportDgv.GetClipboardContent());
}

//创建Excel对象
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
return false;
}
//创建Excel工作薄
Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
//创建Excel工作表
Microsoft.Office.Interop.Excel.Worksheet xlSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBook.Worksheets[1];//第1个工作表
//粘贴数据
xlSheet.get_Range("A1", System.Type.Missing).PasteSpecial(XlPasteType.xlPasteAll,
XlPasteSpecialOperation.xlPasteSpecialOperationNone,
System.Type.Missing, System.Type.Missing);

//显示工作薄区间
xlApp.Visible = true;
xlApp.Caption = DgvTitle;
//设置文本表格的属性
xlApp.Cells.EntireColumn.AutoFit();//自动列宽
xlApp.Cells.VerticalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;
xlApp.Cells.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlLeft;
xlApp.ErrorCheckingOptions.BackgroundChecking = false;
return true;

}
catch
{
return false;
}
}


/// <summary>
/// DataGridView中的所有数据导出到Excel
/// </summary>
/// <param name="ExportDgv">需要导出的DataGridView</param>
/// <param name="fullFileName">导出后的文件全路径</param>
/// <param name="isOpenFile">文件是否打开</param>
/// <returns></returns>
public bool OutputFileToExcel(DataGridView ExportDgv, string fullFileName, bool isOpenFile)
{
int id=0;
bool ExportSuccess = false;

int RowIndex = 0;
int ColIndex = 0;
//数据验证
if (ExportDgv==null)
{
return false;
}
if (ExportDgv.ColumnCount==0|| ExportDgv.RowCount==0)
{
return false;
}
if (ExportDgv.RowCount > 65536 || ExportDgv.ColumnCount > 256)
{
return false;
}


//有效的行数、列数
int rowCount = ExportDgv.Rows.GetRowCount(DataGridViewElementStates.Visible);
int colCount = ExportDgv.Columns.GetColumnCount(DataGridViewElementStates.Visible);

Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
return false;
}
//创建Excel工作薄
Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
//创建Excel工作表
Microsoft.Office.Interop.Excel.Worksheet xlSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBook.Worksheets[1];//第1个工作表

Microsoft.Office.Interop.Excel.Range range;

IntPtr intp=new IntPtr(xlApp.Hwnd);

//定义一个缓存,用来存放DataGridView的数据
object[,] objData = new object[rowCount + 1, colCount];


//1.存放DataGridView的列题行,隐藏列不要
for (int i = 0; i < ExportDgv.Columns.Count; i++)
{
if (ExportDgv.Columns[i].Visible)
{
objData[RowIndex, ColIndex++] = ExportDgv.Columns[i].HeaderText;//将列标题放入缓存中

//设置成文本型
if (ExportDgv.Columns[i].ValueType.ToString()=="System.String")
{
range = xlSheet.get_Range(xlApp.Cells[1, ColIndex], xlApp.Cells[rowCount + 1, ColIndex]);
range.NumberFormat = "@";
}
}
}
//2.存放DataGridView中的数据,
for (int i = 1; i < rowCount; i++)
{
RowIndex++;
ColIndex = 0;
for (int j = 0; j < ExportDgv.Columns.Count; j++)
{
if (ExportDgv.Columns[j].Visible)
{
objData[RowIndex, ColIndex++] = ExportDgv[j, RowIndex - 1].Value;
}
}
System.Windows.Forms.Application.DoEvents();
}

//3.写入到Excel
range = xlSheet.get_Range(xlApp.Cells[1, 1], xlApp.Cells[rowCount + 1, colCount]);
range.Value2 = objData;

//保存
try
{
//设置文本表格的属性
xlApp.Cells.EntireColumn.AutoFit();//自动列宽
xlApp.Cells.VerticalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;
xlApp.Cells.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlLeft;
xlApp.ErrorCheckingOptions.BackgroundChecking = false;

//设置列头
range = xlSheet.get_Range(xlApp.Cells[1, 1], xlApp.Cells[1, colCount]);//第一行数据,列标题
range.Font.Bold = true;
range.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;
xlBook.Save();
xlBook.SaveCopyAs(fullFileName);
ExportSuccess = true;

}
catch
{
ExportSuccess = false;
}
finally
{
//释放资源,关闭进程
xlApp.Quit();
GetWindowThreadProcessId(intp, out id);
System.Diagnostics.Process P = System.Diagnostics.Process.GetProcessById(id);
P.Kill();
}
if (isOpenFile) //打开文件
{
HR.Class.IO.FileOperat FP = new HR.Class.IO.FileOperat();
FP.OpenFile(fullFileName);
}
return ExportSuccess;
}

/// <summary>
/// DataGridView中选中的数据复制到Word
/// </summary>
/// <param name="ExportDgv"></param>
/// <param name="WordTitle"></param>
/// <returns></returns>
public bool OutputFileToWord(DataGridView ExportDgv, string WordTitle)
{
try
{
if (ExportDgv == null)
{
return false;
}

if (ExportDgv.Columns.Count == 0 || ExportDgv.Rows.Count == 0)
{
return false;
}

//复制数据到Clipboard
int I = ExportDgv.GetCellCount(DataGridViewElementStates.Selected);
if (I > 0)
{
//为了解决极少部分机器中文字符乱码问题
//一般为"区域选项,字符集设置不一样的问题
//Clipboard.SetDataObject(ExportGrid.GetClipboardContent());
Clipboard.SetText(ExportDgv.GetClipboardContent().GetData(DataFormats.Text).ToString());
}
else
{
return false;
}

//创建Word对象
object iMissing = System.Type.Missing;
Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
if (wordApp==null)
{
return false;
}
Microsoft.Office.Interop.Word.Document wordDoc = wordApp.Documents.Add(ref iMissing,ref iMissing,ref iMissing,ref iMissing);
//粘贴数据
wordDoc.ActiveWindow.Selection.PasteSpecial(ref iMissing, ref iMissing, ref iMissing, ref iMissing, ref iMissing, ref iMissing, ref iMissing);
wordApp.Caption = WordTitle;
wordApp.Visible = true;//显示粘贴的数据
return true;
}
catch
{
return false;
}
}
}

/// <summary>
/// DataGridView多选选中求和
/// </summary>
public class MultiSelectSum
{
/// <summary>
/// DataGridView选中的单元格求和
/// </summary>
/// <param name="dgv"></param>
/// <param name="toolTip"></param>
public bool DataGridViewSelectCellsSum(DataGridView dgv, ToolTip toolTip)
{
//verify
if (dgv.SelectedCells.Count < 2 )
{
toolTip.RemoveAll();
return false;
}
//选中的单元格大于10000个或者DataGridView是全选
if (dgv.SelectedCells.Count > 10000 || dgv.SelectedCells.Count == dgv.GetCellCount(DataGridViewElementStates.None))
{
toolTip.RemoveAll();
return false;
}

DataSet Ds = new DataSet();
System.Data.DataTable DGroup = new System.Data.DataTable("DGroup");// 存放列名
System.Data. DataTable Dt = new System.Data.DataTable("Dt");//存放列名和数值
ArrayList MaxNameLength=new ArrayList(); //保存列名的长度
ArrayList MaxValueLength=new ArrayList();//保存数值的长度

DGroup.Columns.Add("ColumnName", typeof(string));
Dt.Columns.Add("ColumnName", typeof(string));
Dt.Columns.Add("ColumnValue", typeof(decimal));

DataRow dr = null;
//遍历选中单元格的值
foreach (DataGridViewCell cell in dgv.SelectedCells)
{
dr = Dt.NewRow();

if (cell.ValueType.Name.ToString().ToLower()=="decimal" || cell.ValueType.Name.ToString().ToLower()=="int32")
{


dr["ColumnName"] = dgv.Columns[cell.ColumnIndex].Name;
if (cell.Value == null)
{
dr["ColumnValue"] = 0;
}
else
{
dr["ColumnValue"] = cell.Value.ToString();
MaxValueLength.Add(cell.Value.ToString().Length);
}

Dt.Rows.Add(dr);


//判断将要添加进去的列值是否在DGroup中已存在
if (DGroup.Select("ColumnName='" + dgv.Columns[cell.ColumnIndex].Name + "'").Length == 0)
{
DataRow dr1 = DGroup.NewRow();
dr1["ColumnName"] = dgv.Columns[cell.ColumnIndex].Name;
DGroup.Rows.Add(dr1);
MaxNameLength.Add(dgv.Columns[cell.ColumnIndex].Name.Length);

}
}
}

Ds.Tables.Add(DGroup);
Ds.Tables.Add(Dt);

DataRelation dRelation = new DataRelation("dataRel", Ds.Tables["DGroup"].Columns["ColumnName"], Ds.Tables["Dt"].Columns["ColumnName"]);
Ds.Relations.Add(dRelation);
DGroup.Columns.Add("ColumnSum").Expression = "sum(child(dataRel).ColumnValue)";//添加一个总计列,并对各列求值
string desSum = Dt.Compute("sum(ColumnValue)", "").ToString();//求Dt表ColumnValue列的总计

MaxNameLength.Add("总合计:".Length);
MaxValueLength.Add(desSum.Length);

DGroup.AcceptChanges();//提交对DGroup表的修改

MaxNameLength.Sort();
MaxValueLength.Sort();
int MaxNameLen; //保存最大列名长度
int MaxValueLen;//保存最大数值长度
MaxNameLen = Convert.ToInt32(MaxNameLength[MaxNameLength.Count - 1]);
MaxValueLen = Convert.ToInt32(MaxValueLength[MaxValueLength.Count - 1]);

string title = "";//提示信息
for (int i = 0; i < DGroup.Rows.Count; i++)
{
string strOneLine = "";
strOneLine = (DGroup.Rows[i]["ColumnName"].ToString()+":").PadRight(MaxNameLen + 1, ' ');
strOneLine = strOneLine + (DGroup.Rows[i]["ColumnSum"].ToString()).PadLeft(MaxValueLen, ' ');
title = title + strOneLine + System.Environment.NewLine;//换行

}
title = title + "总合计:".PadRight(MaxNameLen + 1, ' ') + desSum.PadLeft(MaxNameLen + 1, ' ');

dgv.ShowCellToolTips = false;

toolTip.ToolTipIcon = ToolTipIcon.Info;
toolTip.ToolTipTitle = "鼠标选定合计信息:";
toolTip.IsBalloon = true;//气球形状
toolTip.UseAnimation = true;
toolTip.AutoPopDelay = 10000;
toolTip.RemoveAll();
toolTip.SetToolTip(dgv,title );
DGroup.Dispose();
Dt.Dispose();
GC.Collect();
return true;

}

}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
开发环境为vs2012 C#源码及完全样例 此版本为2012.2.24日更新版本,更新内容为 * 最后修改时间:2012.2.24 增加了汇总信息的自定义控制属性,参见功能描述12 * 2012.2.23 修改了过多列时父标题不显示的问题,重新写了算法,修改了标题头重叠及不能换行的问题,参见说明11. 总功能列举如下: /**************************************************************************************************** * Copyright (C) 2012 明振居士 版权没有,任意拷贝及使用,但对使用造成的任何后果不负任何责任,互相开源影响,共同进步 * 文 件 名:DataGridViewEx.cs * 创 建 人:明振居士 * Email:[email protected] qq:342155124 * 创建时间:2010-06-01 * 最后修改时间:2012.2.24 增加了汇总信息的自定义控制属性,参见功能描述12 * 2012.2.23 修改了过多列时父标题不显示的问题,重新写了算法,修改了标题头重叠及不能换行的问题,参见说明11. * 2012-1-19 增加第10条所示的功能;修改了列头超过26列的错误,导出excel为数组方式,速度更快,导出的单元格设置为文本格式。 * 标 题:用户自定义的DataGridView控件 * 功能描述:扩展DataGridView控件功能 * 扩展功能: * 1、搜索Search(); 有两个同明方法,参数不同 F3为快捷键继续向下搜索 * 2、用TreeView HeadSource 来设置复杂的标题样式,如果某个节点对应的显示列隐藏,请将该节点Tag设置为hide,隐藏列的排列位置与绑定数据元列位置对应,树叶节点的顺序需要与结果集的列顺序一致 * 3、通过反射导出Excel,无需引用com组件,方法ExportExcel() ,不受列数的限制,表头同样可以导出,AutoFit属性设置导出excel后是否自动调整单元格宽度 * 导出内容支持自定义的:Title List Header List Footer,支持在设计时值的设定,窗口关闭时Excel资源自动彻底释放 * 4、可以自己任意设定那些列显示及不显示,通过调用方法SetColumnVisible()实现。 * 5、设置列标题SetHeader(),设置列永远可见AlwaysShowCols(),设置列暂时不可见HideCols() * 注意,当使用了TreeView作为复杂Header时,不要使用本方法,Header显示的内容根据treeview内容而显示 * 6、列宽度及顺序的保存SaveGridView(),加载LoadGridView() * 7、支持所见即所得的打印功能,举例如下 * private void button5_Click(object sender, EventArgs e) { DGVPrinter printer = new DGVPrinter(); printer.PrintPreviewDataGridView(DataGridViewEx1); } * 8、自定义合并行与列,行合并用 MergeRowColumn 属性,列合并用MergeColumnNames属性,都可以定义多个列 * 9、行标号的设置 bool ShowRowNumber; * 10、增加最后一行的汇总行,支持列的聚合函数,参见http://msdn.microsoft.com/zh-cn/library/system.data.datacolumn.[removed]v=VS.100).aspx * 假设对id列显示“合计”字符,avgPrice进行平均值,total列显示合计,则对ComputeColumns属性增加三行内容:id,合计:;avgPrice,Avg(avgPrice);total,Sum(total) * 如果需要对值进行格式控制,请实现beforeShow事件 * 增加了导出和打印对应的支持,所见即所得的对齐方应用于式导出及打印。 * 11、列标题头自动换行,默认设置为每个列标题头行高为22,如果设置的字体更大,将自动进行计算。如果需要多行显示,请根据需要调节ColumnHeaderHeight属性值, * 其估算方法为预计的标题头层数乘以22,或层数乘以设置的字体高度。 * 12、针对第10条功能,增加汇总信息的自定义控制属性,汇总字体SummaryFont,汇总字体颜色SummaryFontColor,汇总背景色SummaryBGColor,边框与整个表格边框一致 ****************************************************************************************************/

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值