//用于DataGridView和excel进行互操作的C#类
// 文件名: Excel2DataGridView
// 文件功能描述: C#中DataGridView控件和Excel互访问类,
// 当前版本:V1.0.0
//
//----------------------------------------------------------------*/
/*
public string mFilename;
public Excel.Application app;
public Excel.Workbooks wbs;
public Excel.Workbook wb;
public Excel.Worksheets wss;
public Excel.Worksheet ws;
/// 构造函数,不创建Excel工作薄
public ExcelEdit()
/// 创建Excel工作薄
public void Create()//创建一个Excel对象
/// 显示Excel
public void ShowExcel()
/// 打开一个存在的Excel文件
public void Open(string FileName)//打开一个Excel文件
public Excel.Worksheet GetSheet(string SheetName)
//获取一个工作表
public Excel.Worksheet AddSheet(string SheetName)
//添加一个工作表
public void DelSheet(string SheetName)//删除一个工作表
public Excel.Worksheet ReNameSheet(string OldSheetName, string NewSheetName)//重命名一个工作表一
public Excel.Worksheet ReNameSheet(Excel.Worksheet Sheet, string NewSheetName)//重命名一个工作表二
//把EXCEl中的某工作表显示到datagridview中
public void Excel2DBView(string tablename, DataGridView dataGridView1)
//把EXCEl中的某工作表中字段值为FieldNameStr的行显示到datagridview中
public void Excel2DBView_SelectFieldValue(string tablename, string FieldName, string FieldNameStr, DataGridView dataGridView1)
//返回excel中不把第一行当做标题看待的数据集
public DataSet GetNewDataSet(string tablename)
//根据字段名,删除EXCEl中的某工作表中的记录(SQL语句未成功执行)
public void DeleteExcelFieldValue(string tablename, string FieldName, string FieldNameStr)
/// 在工作表中插入行,并调整其他行以留出空间
public void InsertRows(Excel.Worksheet sheet, int rowIndex)
/// 在工作表中删除行
public void DeleteRows(Excel.Worksheet sheet, int rowIndex)
/// 在工作表中删除所有行名为rowText的行
public void DeleteRows(string sheetName, string FieldName, string rowText)
/// 根据字段名, /// 根据字段名,追加记录
public void AddRecords(string sheetName, string FieldName, string recordText)
/// DataGridView导出到Excel
//获取字段中的字段名称集
public StringCollection GetFieldValues(string sheetName,string FieldName)
public void DGView2Excel(DataGridView dgv, string xlsFileName, string sheetName)
/// DataGridView追加到Excel指定表格中
public void DGViewAdd2Excel(DataGridView dgv, string xlsFileName, string sheetName)
public StringCollection countexcel(string _filename) //返回工作表名
public DataSet proces(string _filename) //用datset返回整个excel
public int rowcount(string _filename, string sheetname) //行数
public int rowcount(string sheetname) //行数
public int colcount(string _filename, string sheetname) //列数
public int colcount(string sheetname) //列数
public string GetCellStr(string sheetName, int row, int col) //返回指定单元格的文本
public void SetCellStr(string sheetName, int row, int col, string writeStr) //将字符串写入指定单元格
public void WriteData(string[,] data, string fileName, string sheetName, int startRow, int startColumn)
/// 将数据写入Excel
public void WriteData(string data, string fileName, string sheetName, int row, int column)
/// 读取指定单元格数据
public string ReadData(string fileName, string sheetName, int row, int column)
public void UniteCells(Excel.Worksheet ws, int x1, int y1, int x2, int y2)
//合并单元格
public void UniteCells(string ws, int x1, int y1, int x2, int y2)
//合并单元格
public void InsertTable(System.Data.DataTable dt, string ws, int startX, int startY)
//将内存中数据表格插入到Excel指定工作表的指定位置 为在使用模板时控制格式时使用一
public void InsertTable(System.Data.DataTable dt, Excel.Worksheet ws, int startX, int startY)
//将内存中数据表格插入到Excel指定工作表的指定位置二
public void AddTable(System.Data.DataTable dt, string ws, int startX, int startY)
//将内存中数据表格添加到Excel指定工作表的指定位置一
public void AddTable(System.Data.DataTable dt, Excel.Worksheet ws, int startX, int startY)
//将内存中数据表格添加到Excel指定工作表的指定位置二
/// 保存Excel
public bool Save()
/// Excel文档另存为
public bool SaveAs(object FileName)
//去掉文件后缀
public void RemoveExefilter(string FileName)
public void Close()
//关闭一个Excel对象,销毁对象
public void release_xlsObj()
//////如何杀死word,excel等进程,下面的方法可以直接调用
public void KillProcess(string processName)
*/
//引入Excel的COM组件
using System;
//using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
//using Microsoft.Office.Interop;
using Microsoft.Office.Core;
//using Excel = Microsoft.Office.Interop.Excel;
//using Excel = Microsoft.Office.Interop.Excel;
using Excel;
using System.Data;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Reflection; // 引用这个才能使用Missing字段
using System.Collections.Specialized;
using System.Runtime.InteropServices;
namespace ExcelEditClass
{
/// <SUMMARY>
/// ExcelEdit 的摘要说明
/// </SUMMARY>
public class ExcelEdit
//public class ExcelEdit:Excel.ApplicationClass //liuxfu
{ //to kill excel
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
public string mFilename;
public Excel.Application app;
public Excel.Workbooks wbs;
public Excel.Workbook wb;
public Excel.Worksheets wss;
public Excel.Worksheet ws;
/// <summary>
/// 构造函数,不创建Excel工作薄
/// </summary>
public ExcelEdit()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 创建Excel工作薄
/// </summary>
public void Create()//创建一个Excel对象
{
try
{
app = new Excel.Application();
wbs = app.Workbooks;
wb = wbs.Add(true);
}
catch (Exception e)
{ MessageBox.Show(e.Message.ToString()); }
}
/// <summary>
/// 显示Excel
/// </summary>
public void ShowExcel()
{
app.Visible = true;
}
/// <summary>
/// 打开一个存在的Excel文件
/// </summary>
/// <param name="FileName">Excel完整路径加文件名</param>
public void Open(string FileName)//打开一个Excel文件
{
try
{
app = new Excel.Application();
wbs = app.Workbooks;
wb = wbs.Add(FileName);
//wb = wbs.Open(FileName, 0, true, 5,"", "", true, Excel.XlPlatform.xlWindows, "t", false, false, 0, true,Type.Missing,Type.Missing);
//wb = wbs.Open(FileName,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Excel.XlPlatform.xlWindows,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);
mFilename = FileName;
//设置禁止弹出保存和覆盖的询问提示框
app.DisplayAlerts = false;
app.AlertBeforeOverwriting = false;
app.UserControl = true;//如果只想用程序控制该excel而不想让用户操作时候,可以设置为false
}
catch (Exception e)
{ MessageBox.Show(e.Message.ToString()); }
}
public Excel.Worksheet GetSheet(string SheetName)
//获取一个工作表
{
Excel.Worksheet s = (Excel.Worksheet)wb.Worksheets[SheetName];
return s;
}
public Excel.Worksheet AddSheet(string SheetName)
//添加一个工作表
{
Excel.Worksheet s = (Excel.Worksheet)wb.Worksheets.Add(Type.Missing,Type.Missing,Type.Missing,Type.Missing);
try
{ s.Name = SheetName;
return s;
}
catch {
return null;
}
}
public void DelSheet(string SheetName)//删除一个工作表
{
try
{
((Excel.Worksheet)wb.Worksheets[SheetName]).Delete();
}
catch (Exception e)
{ MessageBox.Show(e.Message.ToString()); }
}
public Excel.Worksheet ReNameSheet(string OldSheetName, string NewSheetName)//重命名一个工作表一
{
Excel.Worksheet s = (Excel.Worksheet)wb.Worksheets[OldSheetName];
try { s.Name = NewSheetName;
return s;
}
catch (Exception e)
{ MessageBox.Show(e.Message.ToString());
return null;
}
}
public Excel.Worksheet ReNameSheet(Excel.Worksheet Sheet, string NewSheetName)//重命名一个工作表二
{
try { Sheet.Name = NewSheetName;
return Sheet;
}
catch (Exception e)
{ MessageBox.Show(e.Message.ToString());
return null;
}
}
//_____________________________ole自定义函数___________________________________________________________________________
//______________________________excel和datagridview之间互操作函数_______________________________________________________
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//把EXCEl中的某工作表显示到datagridview中
/// <summary>
/// ExcelEdit myExcel = new ExcelEdit();
/// myExcel.Open("d://数据库表格20071217.xls");
/// myExcel.Excel2DBView("908", this.dataGridView1);
/// myExcel.Close();
/// </summary>
/// <param name="tablename"></param>
/// <param name="dataGridView1"></param>
public void Excel2DBView(string xlsFilaName,string tablename, DataGridView dataGridView1)
{
try
{
string sExcelFile = xlsFilaName;
//string strExcelFileName = @""+ myPath +"";
//string strString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = " + strExcelFileName + ";Extended Properties = 'Excel 8.0;HDR=NO;IMEX=1 '";
//string sConnectionString = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=" + sExcelFile + ";Extended Properties=Excel 8.0;";
string sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sExcelFile + ";Extended Properties=/"Excel 8.0;HDR=NO;IMEX=1/"";
OleDbConnection connection = new OleDbConnection(sConnectionString);
string sql_select_commands = "Select * from [" + tablename + "$]";
OleDbDataAdapter adp = new OleDbDataAdapter(sql_select_commands, connection);
DataSet ds = new DataSet();
adp.Fill(ds, tablename);
dataGridView1.Rows.Clear();
dataGridView1.Columns.Clear();
//写入dataGridView控件标题
for (int j = 0; j < ds.Tables[tablename].Columns.Count; j++)
{
dataGridView1.Columns.Add(ds.Tables[tablename].Rows[0][j].ToString(), ds.Tables[tablename].Rows[0][j].ToString());
}
for (int i = 1; i < ds.Tables[tablename].Rows.Count; i++)
{
dataGridView1.Rows.Add();
}
//写入dataGridView控件行数据
for (int i = 1; i < ds.Tables[tablename].Rows.Count; i++)
for (int j = 0; j < ds.Tables[tablename].Columns.Count; j++)
{
dataGridView1.Rows[i - 1].Cells[j].Value = Convert.ToString(ds.Tables[tablename].Rows[i][j]);
}
}
catch (Exception e)
{ MessageBox.Show(e.Message.ToString()); }
/*
for (int i = 0; i < ds.Tables["Book1"].Rows.Count; i++)
{
sum1 += Convert.ToInt32(ds.Tables["Book1"].Rows[i]["字段A"]);
}
for (int j = 0; j < ds.Tables["Book1"].Rows.Count; j++)
{
sum2 += Convert.ToInt32(ds.Tables["Book1"].Rows[j]["字段B"]);
}
MessageBox.Show(sum1.ToString() + " and " + sum2.ToString());
* */
/*
*备注:
* 用OLEDB进行Excel文件数据的读取,并返回DataSet数据集。其中有几点需要注意的:
1.连接字符串中参数IMEX 的值:
0 is Export mode 1 is Import mode 2 is Linked mode (full update capabilities)
IMEX有3个值:当IMEX=2 时,EXCEL文档中同时含有字符型和数字型时,比如第C列有3个值,2个为数值型 123,1个为字符型 ABC,当导入时,
页面不报错了,但库里只显示数值型的123,而字符型的ABC则呈现为空值。当IMEX=1时,无上述情况发生,库里可正确呈现 123 和 ABC.
2.参数HDR的值:
HDR=Yes,这代表第一行是标题,不做为数据使用 ,如果用HDR=NO,则表示第一行不是标题,做为数据来使用。系统默认的是YES
3.参数Excel 8.0
对于Excel 97以上版本都用Excel 8.0
@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/MyExcel.xls;Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"""
"HDR=Yes;" indicates that the first row contains columnnames, not data
"IMEX=1;" tells the driver to always read "intermixed" data columns as text
TIP! SQL syntax: "SELECT * FROM [sheet1$]" - i.e. worksheet name followed by a "$" and wrapped in "[" "]" brackets.
如果第一行是数据而不是标题的话, 应该写: "HDR=No;"
"IMEX=1;" tells the driver to always read "intermixed" data columns as text
* */
/*
你可以先用代码打开xls文件:
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("d:/text2.xls")
for i=0 to xlBook.Worksheets.Count-1
set xlSheet = xlBook.Worksheets(i)
xlSheet.Name //这就是你需要的每个sheet的名字,保存起来,备后用
next i
这里使用的VB写的范例,变成c#即可.
*/
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//把EXCEl中的某工作表中字段值为FieldNameStr的行显示到datagridview中
/// <summary>
/// </summary>
/// <param name="tablename"></param>
/// <param name="FieldValueStr"></param>
/// <param name="dataGridView1"></param>
public void Excel2DBView_SelectFieldValue(string tablename,string FieldName,string FieldNameStr,DataGridView dataGridView1)
{
string sExcelFile = mFilename;
try
{
string sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sExcelFile + ";Extended Properties=/"Excel 8.0;HDR=Yes;IMEX=1/"";
OleDbConnection connection = new OleDbConnection(sConnectionString);
string sql_select_commands = "select * from ["+tablename+"$] where "+FieldName+"=" + FieldNameStr;
//MessageBox.Show(sql_select_commands);
OleDbDataAdapter adp = new OleDbDataAdapter(sql_select_commands, connection);
DataSet ds = new DataSet();
adp.Fill(ds, tablename);
//设置DataGridView控件的字段标题
DataSet ds2 = new DataSet();
ds2 = GetNewDataSet(tablename);
for (int j = 0; j < ds2.Tables[tablename].Columns.Count; j++)
{
dataGridView1.Columns.Add(ds2.Tables[tablename].Rows[0][j].ToString(), ds2.Tables[tablename].Rows[0][j].ToString());
}
for (int i = 0; i < ds.Tables[tablename].Rows.Count; i++)
{
dataGridView1.Rows.Add();
}
for (int i = 0; i < ds.Tables[tablename].Rows.Count; i++)
for (int j = 0; j < ds.Tables[tablename].Columns.Count; j++)
{
dataGridView1.Rows[i ].Cells[j].Value = Convert.ToString(ds.Tables[tablename].Rows[i][j]);
}
}
catch (Exception e)
{ MessageBox.Show(e.Message.ToString()); }
}
//返回excel中不把第一行当做标题看待的数据集
public DataSet GetNewDataSet(string tablename)
{
string sExcelFile = mFilename;
try
{
string sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sExcelFile + ";Extended Properties=/"Excel 8.0;HDR=NO;IMEX=1/"";
OleDbConnection connection = new OleDbConnection(sConnectionString);
string sql_select_commands = "Select * from [" + tablename + "$]";
OleDbDataAdapter adp = new OleDbDataAdapter(sql_select_commands, connection);
DataSet ds = new DataSet();
adp.Fill(ds, tablename);
return ds;
}
catch (Exception e)
{ MessageBox.Show(e.Message.ToString()); return null; }
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//根据字段名,删除EXCEl中的某工作表中的记录(SQL语句未成功执行)
/// <summary>
/// </summary>
/// <param name="tablename"></param>
/// <param name="FieldValueStr"></param>
/// <param name="dataGridView1"></param>
public void DeleteExcelFieldValue(string tablename, string FieldName, string FieldNameStr)
{
string sExcelFile = mFilename;
try
{
string sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sExcelFile + ";Extended Properties=/"Excel 8.0;HDR=Yes;IMEX=1/"";
OleDbConnection connection = new OleDbConnection(sConnectionString);
string sql_select_commands = "delete from [" + tablename + "$] where " + FieldName + "=" + FieldNameStr;
//string sql_select_commands = "delete from [" + tablename + "$]";
//string sql_select_commands = "drop table [" + tablename + "$]";
MessageBox.Show(sql_select_commands);
OleDbDataAdapter adp = new OleDbDataAdapter(sql_select_commands, connection);
}
catch (Exception e)
{ MessageBox.Show(e.Message.ToString()); }
}
/// 在工作表中插入行,并调整其他行以留出空间
///当前工作表
/// 欲插入的行索引
public void InsertRows(Excel.Worksheet sheet, int rowIndex)
{
Excel.Range range = (Excel.Range)sheet.Rows[rowIndex, Type.Missing];
//object Range.Insert(object shift, object copyorigin);
//shift: Variant类型,可选。指定单元格的调整方式。可以为下列 XlInsertShiftDirection 常量之一:
//xlShiftToRight 或 xlShiftDown。如果省略该参数,Microsoft Excel 将根据区域形状确定调整方式。
range.Insert(Excel.XlInsertShiftDirection.xlShiftDown, Type.Missing);
range=null;
}
/// 在工作表中删除行
///当前工作表
///欲删除的行索引
public void DeleteRows(Excel.Worksheet sheet, int rowIndex)
{
try
{
Excel.Range range = (Excel.Range)sheet.Rows[rowIndex, Type.Missing];
range.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);
range = null;
}
catch (Exception e)
{ MessageBox.Show(e.Message.ToString()); }
}
/// 在工作表中删除所有行名为rowText的行
///当前工作表
///欲删除的行索引
public void DeleteRows(string sheetName,string FieldName,string rowText)
{
Excel.Worksheet worksheet = GetSheet(sheetName);
try
{
if (worksheet == null)
{
throw new Exception("Worksheet error ");
return;
}
//获取工作表行列数
int rowCounts = rowcount(sheetName);
int colCounts = colcount(sheetName);
// MessageBox.Show(rowCounts.ToString() +"|" +colCounts.ToString());
int colIndex = 0;
//定位字段索引
for (int i = 1; i <= colCounts; i++)
{
if (GetCellStr(sheetName, 1, i) == FieldName)
{
colIndex = i;
break;
}
}
if (colIndex == 0)
{
MessageBox.Show("找不到字段名:" + FieldName);
return;
}
//int jj = 0;
//int jjj = 0;
for (int i = 1; i <= rowCounts; i++)
{
//jj++;
if (GetCellStr(sheetName, i, colIndex) == rowText)
{
DeleteRows(worksheet, i);
i--;
rowCounts = rowCounts - 1;
//jjj++;
}
}
}
catch (Exception e)
{ MessageBox.Show(e.Message.ToString()); }
}
/// 根据字段名,追加记录
public void AddRecords(string sheetName, string FieldName, string recordText)
{
Excel.Worksheet worksheet = GetSheet(sheetName);
try
{
if (worksheet == null)
{
throw new Exception("Worksheet error ");
return;
}
//获取工作表行列数
int rowCounts = rowcount(sheetName);
int colCounts = colcount(sheetName);
// MessageBox.Show(rowCounts.ToString() +"|" +colCounts.ToString());
int colIndex = 0;
//定位字段索引
for (int i = 1; i <= colCounts; i++)
{
if (GetCellStr(sheetName, 1, i) == FieldName)
{
colIndex = i;
break;
}
}
if (colIndex == 0)
{
MessageBox.Show("找不到字段名:" + FieldName);
return;
}
SetCellStr(sheetName, rowCounts + 1, colIndex, recordText);
}
catch (Exception e)
{ MessageBox.Show(e.Message.ToString()); }
}
//获取字段中的字段名称集
public StringCollection GetFieldValues(string sheetName,string FieldName)
{
Excel.Worksheet worksheet = GetSheet(sheetName);
if (worksheet == null)
{
throw new Exception("Worksheet error ");
return null;
}
//获取工作表行列数
int rowCounts = rowcount(sheetName);
int colCounts = colcount(sheetName);
// MessageBox.Show(rowCounts.ToString() +"|" +colCounts.ToString());
int colIndex = 0;
//定位字段索引
for (int i = 1; i <= colCounts; i++)
{
if (GetCellStr(sheetName, 1, i) == FieldName)
{
colIndex = i;
break;
}
}
if (colIndex == 0)
{
MessageBox.Show("找不到字段名:" + FieldName);
return null;
}
StringCollection fieldStrs = new StringCollection();
string cellStr;
for (int i = 2; i <= rowCounts; i++)
{
cellStr=GetCellStr(sheetName, i, colIndex);
if (!fieldStrs.Contains(cellStr))
{
fieldStrs.Add(cellStr);
}
}
return fieldStrs;
}
/// DataGridView导出到Excel
/// ExcelEdit myExcel = new ExcelEdit();
/// myExcel.Create();
/// myExcel.DGView2Excel(this.dataGridView1, "d://xiao.xls", "xiaobiao");
/// myExcel.Save();
/// myExcel.Close();
public void DGView2Excel(DataGridView dgv, string sheetName)
{
try
{
int rowCount = dgv.RowCount;
int columnCount = dgv.ColumnCount;
//Excel.Workbooks workbook=(Excel.Workbook)app
//Open(xlsFileName);
Excel.Worksheet worksheet = GetSheet(sheetName);
int sheet_rowCounts = rowcount(sheetName);
int sheet_colCounts = colcount(sheetName);
//int rowIndex = 0;
if (worksheet == null)
{
throw new Exception("Worksheet error ");
}
//
Excel.Range r = worksheet.get_Range("A1 ", Missing.Value);
if (r == null)
{
MessageBox.Show("Range无法启动 ");
throw new Exception("Range error ");
}
//以上是一些例行的初始化工作,下面进行具体的信息填充
//填充标题
int ColIndex = 1;
foreach (DataGridViewColumn dHeader in dgv.Columns)
{
worksheet.Cells[1, ColIndex++] = dHeader.HeaderText;
//worksheet.Cells[21, ColIndex++] = dHeader.HeaderText;
}
ColIndex = 1;
//获取DataGridView中的所有行和列的数值,填充到一个二维数组中.
object[,] myData = new object[rowCount + 1, columnCount];
for (int i = 0; i < rowCount; i++)
{
for (int j = 0; j < columnCount; j++)
{
myData[i, j] = dgv[j, i].Value; //这里的获取注意行列次序
}
}
//将填充好的二维数组填充到Excel对象中.
r = worksheet.get_Range(worksheet.Cells[2, 1], worksheet.Cells[rowCount + 1, columnCount]);
r.Value2 = myData;
r = null;
}
catch (Exception e)
{ MessageBox.Show(e.Message.ToString()); }
}
/// DataGridView追加到Excel指定表格中
/// ExcelEdit myExcel = new ExcelEdit();
/// myExcel.Create();
/// myExcel.DGViewAdd2Excel(this.dataGridView1, "d://xiao.xls", "xiaobiao");
/// myExcel.Save();
/// myExcel.Close();
public void DGViewAdd2Excel(DataGridView dgv, string sheetName)
{
try
{
//DataGridView控件行列数
int rowCount = dgv.RowCount;
int columnCount = dgv.ColumnCount;
//工作表行列数
int sheet_row_count = rowcount(sheetName);
int sheet_column_count = colcount(sheetName);
// MessageBox.Show(sheet_row_count.ToString() + " | "+sheet_column_count.ToString());
//Excel.Workbooks workbook=(Excel.Workbook)app
//Open(xlsFileName);
Excel.Worksheet worksheet = GetSheet(sheetName);
if (worksheet == null)
{
throw new Exception("Worksheet error ");
}
//
Excel.Range r = worksheet.get_Range("A1 ", Missing.Value);
if (r == null)
{
MessageBox.Show("Range无法启动 ");
throw new Exception("Range error ");
}
//以上是一些例行的初始化工作,下面进行具体的信息填充
//填充标题
int ColIndex = 1;
foreach (DataGridViewColumn dHeader in dgv.Columns)
{
worksheet.Cells[1, ColIndex++] = dHeader.HeaderText;
}
ColIndex = 1;
//获取DataGridView中的所有行和列的数值,填充到一个二维数组中.
object[,] myData = new object[rowCount + 1, columnCount];
for (int i = 1; i < rowCount; i++)
{
for (int j = 0; j <columnCount; j++)
{
myData[i-1, j] = dgv[j, i-1].Value; //这里的获取注意行列次序
}
}
//将填充好的二维数组填充到Excel对象中.
//r = worksheet.get_Range(worksheet.Cells[sheet_row_count + 1, 1], worksheet.Cells[sheet_row_count + rowCount, columnCount]);
r = worksheet.get_Range(worksheet.Cells[sheet_row_count+1, 1], worksheet.Cells[sheet_row_count+ rowCount, columnCount]);
r.Value2 = myData;
r = null;
}
catch (Exception e)
{ MessageBox.Show(e.Message.ToString()); }
}
//_________________________________________________________________________________
public StringCollection countexcel(string _filename) //返回工作表名
{
if (System.IO.File.Exists(_filename))
{
Excel.ApplicationClass myExcelApp = new Excel.ApplicationClass();
Excel.Workbook excel_wb;
excel_wb = myExcelApp.Workbooks.Open(_filename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
StringCollection a = new StringCollection();
for (int i = 1; i <= excel_wb.Worksheets.Count; i++)
{
a.Add(((Excel.Worksheet)excel_wb.Worksheets[i]).Name);
}
myExcelApp.Workbooks.Close();
myExcelApp.Quit();
myExcelApp = null;
return a;
}
else
{
return null;
}
}
public DataSet proces(string _filename) //用datset返回整个excel
{
string strConn = "Provider=Microsoft.Jet.OleDb.4.0;";
strConn += "data source=" + _filename + ";";
strConn += "Extended Properties=Excel 8.0;";
strConn += "HDR=Yes;IMEX=1";
OleDbConnection objConn = new OleDbConnection(strConn);
DataSet ds = new DataSet();
OleDbDataAdapter oldda = new OleDbDataAdapter();
foreach (string sheetname in countexcel(_filename))
{
string a = "select * from ";
a += sheetname;
oldda.SelectCommand.CommandText = a;
oldda.Fill(ds, sheetname);
}
return ds;
}
public int rowcount(string _filename,string sheetname) //行数
{
Excel.ApplicationClass myExcelApp = new Excel.ApplicationClass();
Excel.Workbook excel_wb;
excel_wb = myExcelApp.Workbooks.Open(_filename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
int counts = ((Excel.Worksheet)excel_wb.Worksheets.get_Item(sheetname)).UsedRange.Rows.Count;
myExcelApp.Workbooks.Close();
myExcelApp.Quit();
myExcelApp = null;
return counts;
}
public int rowcount(string sheetname) //行数
{
Excel.Worksheet worksheet = GetSheet(sheetname);
if (worksheet == null)
{
throw new Exception("Worksheet error ");
}
int counts=worksheet.UsedRange.Rows.Count;
worksheet = null;
return counts;
}
public int colcount(string _filename, string sheetname) //列数
{
Excel.ApplicationClass myExcelApp = new Excel.ApplicationClass();
Excel.Workbook excel_wb;
excel_wb = myExcelApp.Workbooks.Open(_filename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
int counts = ((Excel.Worksheet)excel_wb.Worksheets.get_Item(sheetname)).UsedRange.Columns.Count;
myExcelApp.Workbooks.Close();
myExcelApp.Quit();
myExcelApp = null;
return counts;
}
public int colcount(string sheetname) //列数
{
Excel.Worksheet worksheet = GetSheet(sheetname);
if (worksheet == null)
{
throw new Exception("Worksheet error ");
}
int counts = worksheet.UsedRange.Columns.Count;
worksheet = null;
return counts;
}
public string GetCellStr(string sheetName, int row, int col) //返回指定单元格的文本
{
string str="";
try
{
//Open(xlsFileName);
Excel.Worksheet worksheet = GetSheet(sheetName);
Excel.Range r = (Excel.Range)(worksheet.Cells[row, col]);
str = r.Text.ToString();
r = null;
worksheet = null;
//Close();
}
catch (Exception e)
{ MessageBox.Show(e.Message.ToString()); }
return str;
//Excel.Range rng3 = xSheet.get_Range("C6", System.Reflection.Missing.Value);
//rng3.Cells.FormulaR1C1 = txtCellText.Text;
// rng3.Interior.ColorIndex = 6; //设置Range的背景色
}
public void SetCellStr(string sheetName, int row, int col,string writeStr) //将字符串写入指定单元格
{
try
{
//Open(xlsFileName);
Excel.Worksheet worksheet = GetSheet(sheetName);
Excel.Range r = (Excel.Range)(worksheet.Cells[row, col]);
//r.Text.FormulaR1C1;
r.Value2 = writeStr;
worksheet = null;
r = null;
}
catch (Exception e)
{ MessageBox.Show(e.Message.ToString()); }
//Save();
// Close();
//Excel.Range rng3 = xSheet.get_Range("C6", System.Reflection.Missing.Value);
//rng3.Cells.FormulaR1C1 = txtCellText.Text;
// rng3.Interior.ColorIndex = 6; //设置Range的背景色
}
//_______________________________________添加自定义函数_________________________________________________________________
/// <summary>
/// 将数据写入Excel
/// </summary>
/// <param name="data">要写入的二维数组数据</param>
/// <param name="startRow">Excel中的起始行</param>
/// <param name="startColumn">Excel中的起始列</param>
public void WriteData(string[,] data, string fileName, string sheetName, int startRow, int startColumn)
{
try
{
Excel.Application myExcel;
Excel.Workbook myWorkBook;
myExcel = new Excel.Application();
//myWorkBook = myExcel.Application.Workbooks.Add(true);
myWorkBook = myExcel.Workbooks.Add(fileName);
Excel.Worksheet worksheet = (Excel.Worksheet)myWorkBook.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
worksheet.Name = sheetName;
//Excel.Worksheet worksheet = (Excel.Worksheet)myExcel.Worksheets[sheetName];
worksheet.Activate();
int rowNumber = data.GetLength(0);
int columnNumber = data.GetLength(1);
for (int i = 0; i < rowNumber; i++)
{
for (int j = 0; j < columnNumber; j++)
{
//在Excel中,如果某单元格以单引号“'”开头,表示该单元格为纯文本,因此,我们在每个单元格前面加单引号。
myExcel.Cells[startRow + i, startColumn + j] = "'" + data[i, j];
}
}
myExcel.Quit();
myWorkBook = null;
myExcel = null;
GC.Collect();
}
catch (Exception e)
{ MessageBox.Show(e.Message.ToString()); }
}
/// <summary>
/// 将数据写入Excel
/// </summary>
/// <param name="data">要写入的字符串</param>
/// <param name="starRow">写入的行</param>
/// <param name="startColumn">写入的列</param>
public void WriteData(string data, string fileName, string sheetName, int row, int column)
{
try
{
Excel.Application myExcel;
Excel.Workbook myWorkBook;
myExcel = new Excel.Application();
//myWorkBook = myExcel.Application.Workbooks.Add(true);
myWorkBook = myExcel.Workbooks.Add(fileName);
Excel.Worksheet worksheet = (Excel.Worksheet)myWorkBook.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
worksheet.Name = sheetName;
//Excel.Worksheet worksheet = (Excel.Worksheet)myExcel.Worksheets[sheetName];
worksheet.Activate();
myExcel.Cells[row, column] = data;
myExcel.Quit();
myWorkBook = null;
myExcel = null;
GC.Collect();
}
catch (Exception e)
{ MessageBox.Show(e.Message.ToString()); }
//Excel.Range rng3 = xSheet.get_Range("C6", System.Reflection.Missing.Value);
//rng3.Cells.FormulaR1C1 = txtCellText.Text;
// rng3.Interior.ColorIndex = 6; //设置Range的背景色
}
/// <summary>
/// 读取指定单元格数据
/// </summary>
/// <param name="row">行序号</param>
/// <param name="column">列序号</param>
/// <returns>该格的数据</returns>
public string ReadData(string fileName,string sheetName,int row, int column)
{
Excel.Application myExcel;
Excel.Workbook myWorkBook;
myExcel = new Excel.Application();
//myWorkBook = myExcel.Application.Workbooks.Add(true);
myWorkBook = myExcel.Workbooks.Add(fileName);
Excel.Worksheet worksheet = (Excel.Worksheet)myWorkBook.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
worksheet.Name = sheetName;
//Excel.Worksheet worksheet = (Excel.Worksheet)myExcel.Worksheets[sheetName];
worksheet.Activate();
Excel.Range range = myExcel.get_Range(myExcel.Cells[row, column], myExcel.Cells[row, column]);
string str = range.Text.ToString();
myExcel.Quit();
myWorkBook = null;
myExcel = null;
GC.Collect();
return str;
}
public void UniteCells(Excel.Worksheet ws, int x1, int y1, int x2, int y2)
//合并单元格
{
ws.get_Range(ws.Cells[x1, y1], ws.Cells[x2, y2]).Merge(Type.Missing);
}
public void UniteCells(string ws, int x1, int y1, int x2, int y2)
//合并单元格
{
GetSheet(ws).get_Range(GetSheet(ws).Cells[x1, y1], GetSheet(ws).Cells[x2, y2]).Merge(Type.Missing);
}
public void InsertTable(System.Data.DataTable dt, string ws, int startX, int startY)
//将内存中数据表格插入到Excel指定工作表的指定位置 为在使用模板时控制格式时使用一
{
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
for (int j = 0; j<= dt.Columns.Count - 1; j++)
{
GetSheet(ws).Cells[startX+i, j + startY] = dt.Rows[i][j].ToString();
}
}
}
public void InsertTable(System.Data.DataTable dt, Excel.Worksheet ws, int startX, int startY)
//将内存中数据表格插入到Excel指定工作表的指定位置二
{
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
for (int j = 0; j <= dt.Columns.Count - 1; j++)
{
ws.Cells[startX+i, j + startY] = dt.Rows[i][j];
}
}
}
public void AddTable(System.Data.DataTable dt, string ws, int startX, int startY)
//将内存中数据表格添加到Excel指定工作表的指定位置一
{
for (int i = 0; i<= dt.Rows.Count - 1; i++)
{
for (int j = 0; j<= dt.Columns.Count - 1; j++)
{
GetSheet(ws).Cells[i + startX, j + startY] = dt.Rows[i][j];
}
}
}
public void AddTable(System.Data.DataTable dt, Excel.Worksheet ws, int startX, int startY)
//将内存中数据表格添加到Excel指定工作表的指定位置二
{
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
for (int j = 0; j <= dt.Columns.Count - 1; j++)
{
ws.Cells[i + startX, j + startY] = dt.Rows[i][j];
}
}
}
/// <summary>
/// 保存Excel
/// </summary>
/// <returns>保存成功返回True</returns>
public bool Save()
//保存文档
{
if (mFilename == "")
{
return false;
}
else
{
try
{
wb.Save();//似乎实效,所以加一下一个语句
wb.SaveAs(mFilename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
return true;
}
catch (Exception e)
{ MessageBox.Show(e.Message.ToString());
return false;
}
}
}
/// <summary>
/// Excel文档另存为
/// </summary>
/// <param name="fileName">保存完整路径加文件名</param>
/// <returns>保存成功返回True</returns>
public bool SaveAs(object FileName)
//文档另存为
{
try
{
wb.SaveAs(FileName,Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
return true;
}
catch (Exception e)
{ MessageBox.Show(e.Message.ToString());
return false;
}
}
//去掉文件后缀
public void RemoveExefilter(string FileName)
{
string filename=FileName;
string substr;
if (System.IO.File.Exists(FileName))
{
System.IO.FileInfo myfile=new System.IO.FileInfo(FileName);
//filename = FileName.Trim(myfile.Extension.ToCharArray());
substr=myfile.Extension;
filename = filename.Substring(0,filename.Length-substr.Length);
//MessageBox.Show(substr);
//MessageBox.Show(filename);
if (System.IO.File.Exists(filename))
{
System.IO.File.Delete(filename);
}
myfile.MoveTo(filename.ToString());
}
}
/// <summary>
/// 关闭Excel
/// </summary>
/// /// <summary>
/// winapi 用于找到句柄线程
/// </summary>
/// <param name="hwnd"></param>
/// <param name="ID"></param>
/// <returns></returns>
public void Close()
//关闭一个Excel对象,销毁对象
{
/*
app.Quit();
//release_xlsObj();
//release_xlsObj();
//wb.Save();
wb.Close(Type.Missing,Type.Missing,Type.Missing);
wbs.Close();
app.Quit();
wb = null;
wbs = null;
app = null;
//KillProcess("EXCEL");
GC.Collect();
*/
app.Quit();
release_xlsObj();
//调用window api查找Excel进程,并用关闭
IntPtr t = new IntPtr(app.Hwnd);
int ProcessById;
GetWindowThreadProcessId(t, out ProcessById);
System.Diagnostics.Process ExcelProcess = System.Diagnostics.Process.GetProcessById(ProcessById);
ExcelProcess.Kill();
app = null;
wbs = null;
wb = null;
wss = null;
ws = null;
}
public void release_xlsObj()
{
//if (app != null)
//System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
//app = null;
if (wbs != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(wbs);
wbs = null;
if (wb != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
wb = null;
if (wss != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(wss);
wss = null;
if (ws != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(ws);
ws = null;
//System.Runtime.InteropServices.Marshal.ReleaseComObject(Range);
// Range=null;
GC.Collect();
}
//////如何杀死word,excel等进程,下面的方法可以直接调用
public void KillProcess(string processName)
{
System.Diagnostics.Process myproc = new System.Diagnostics.Process();
//得到所有打开的进程
try
{
foreach (System.Diagnostics.Process thisproc in System.Diagnostics.Process.GetProcessesByName(processName))
{
if (!thisproc.CloseMainWindow())
{
thisproc.Kill();
}
}
}
catch (Exception e)
{ MessageBox.Show(e.Message.ToString()); }
}
}
}