C#能不能像操作SQL数据库那样使用sql语句对excel进行读取更新等操作?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#能不能像操作SQL数据库那样使用sql语句对excel进行读取更新等操作?相关的知识,希望对你有一定的参考价值。
可以的话谁能给个简单的例子吗?
excel里面字段是怎么设,怎么读取的
还有excel里面由函数计算得出的数值在读取时会怎么样?
这是一个完整的 excel 操作类 ,以前的一个项目用到的 DataSetToExcel
using System;
using System.Windows.Forms;
using System.Data;
using System.Collections;
using System.IO;
using System.Diagnostics;
namespace CHUmanager.MoonCake.Common
/// <summary>
/// DataSetToExcel 的摘要说明。
/// </summary>
public class DataSetToExcel
private DateTime beforeTime; //Excel启动之前时间
private DateTime afterTime; //Excel启动之后时间
public DataSetToExcel()
//
// TODO: 在此处添加构造函数逻辑
//
/// <summary>
/// 导出到Excel
/// </summary>
/// <param name="filename">为要保存的excel文件名</param>
///<param name="GridX">要打开的DataGrid</param>
/// <param name="excelname">excelname为excel表的标题</param>
public bool ExportToExcel(string filename,DataGrid GridX,string excelname)
if(GridX==null) return false;
string saveFileName="";
bool fileSaved=false;
SaveFileDialog saveDialog=new SaveFileDialog();
saveDialog.DefaultExt ="xls";
saveDialog.Filter="Excel文件|*.xls";
saveDialog.FileName =filename;
saveDialog.ShowDialog();
saveFileName=saveDialog.FileName;
if(saveFileName.IndexOf(":")<0) return false; //被点了取消
beforeTime = DateTime.Now;//Excel启动之前时间
Excel.Application excel= new Excel.ApplicationClass(); //启动Excel进程
afterTime = DateTime.Now;//Excel启动之后时间
Excel._Workbook xBk = excel.Workbooks.Add(true);
Excel._Worksheet xSt = (Excel._Worksheet)xBk.ActiveSheet;
Excel.Range excelCell=null;
try
//赋值对象
object[] objarr;
DataTable dtTest=new DataTable();;
int i,j;
int iRows,iCows;
int iVisable;
iVisable=0;
iCows=0;
ArrayList list=new ArrayList();
//如果绑定数据源是DataTable和DataSet,取得行数
if (GridX.DataSource is System.Data.DataTable)
dtTest=(DataTable)GridX.DataSource;
iRows=dtTest.Rows.Count;
else if(GridX.DataSource is System.Data.DataSet)
DataSet ds=(DataSet)GridX.DataSource;
dtTest=ds.Tables[0];
iRows=dtTest.Rows.Count;
else if (GridX.DataSource is System.Data.DataView)
DataView dvTest=(DataView)GridX.DataSource;
iRows=dvTest.Count;
dtTest=dvTest.Table;
//如果是集合取得行数
else
System.Collections.CollectionBase ColTest;
ColTest=(System.Collections.CollectionBase)GridX.DataSource;
iRows=ColTest.Count;
//添加表头
xSt.Cells[1,1] = excelname;
//表头样式
excelCell=(Excel.Range)xSt.Cells[1,1];
excelCell.Interior.ColorIndex = 15;
excelCell.Font.Size = 14;
excelCell.Font.Name = "隶书";
excelCell.Font.Bold = true;
excelCell.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
//如果有TableStyles则根据TableStyles取得(标题行)
if (GridX.TableStyles.Count>0)
list.Clear();
iCows=GridX.TableStyles[0].GridColumnStyles.Count;
for(i=0;i<iCows;i++)
if(GridX.TableStyles[0].GridColumnStyles[i].Width>0)
iVisable++;
list.Add(GridX.TableStyles[0].GridColumnStyles[i].HeaderText);
//获取字段样式
excelCell=(Excel.Range)xSt.Cells[2,i+1];
excelCell.Font.Bold = true;
objarr = new object[iVisable];
objarr=list.ToArray();
excelCell = xSt.get_Range(excel.Cells[2,1],excel.Cells[2,iVisable]);
excelCell.Value2 = objarr;
//数据行
for(i=0;i<iRows;i++)
objarr = new object[iVisable];
list.Clear();
for(j=0;j<iCows;j++)
if(GridX.TableStyles[0].GridColumnStyles[j].Width>0)
list.Add(GridX[i,j].ToString().Replace("\n",""));
if (list.Equals(System.DBNull.Value))
break;
objarr=list.ToArray();
excelCell = xSt.get_Range(excel.Cells[i+3,1],excel.Cells[i+3,iVisable]);
excelCell.Value2 = objarr;
else
iCows=dtTest.Columns.Count;
for(i=0;i<iCows;i++)
list.Add(dtTest.Columns[i].Caption.ToString());
objarr = new object[iCows];
objarr=list.ToArray();
excelCell = xSt.get_Range(excel.Cells[2,1],excel.Cells[2,iCows]);
excelCell.Value2 = objarr;
//数据行
for(i=0;i<iRows;i++)
objarr = new object[iCows];
list.Clear();
for(j=0;j<iCows;j++)
list.Add(GridX[i,j].ToString().Replace("\n",""));
if (list.Equals(System.DBNull.Value))
break;
objarr=list.ToArray();
excelCell = xSt.get_Range(excel.Cells[i+3,1],excel.Cells[i+3,iCows]);
excelCell.Value2 = objarr;
//合并单元格
Excel.Range rH = xSt.get_Range("A1",intToString(iCows)+"1");
rH.Merge(0);
dtTest.Dispose();
if(saveFileName!="")
try
xBk.Saved = true;
xBk.SaveCopyAs(saveFileName);
fileSaved=true;
catch(Exception ex)
fileSaved=false;
MessageBox.Show("导出文件时出错,文件可能正被打开!\n"+ex.Message);
else
fileSaved=false;
catch (System.Exception e)
System.Windows.Forms.MessageBox.Show(e.Message);
finally
excelCell=null;
xBk=null;
xSt=null;
excel=null;
GC.Collect();
KillExcelProcess();//强制结束Excel进程
return fileSaved;
/// <summary>
/// 导出到Excel
/// </summary>
/// <param name="filename">为要保存的excel文件名</param>
/// <param name="dt">dt为关联grid的DataTable</param>
/// <param name="excelname">excelname为excel表的标题</param>
public bool ExportToExcel(string filename,DataTable dt,string excelname)
if(dt==null) return false;
string saveFileName="";
bool fileSaved=false;
SaveFileDialog saveDialog=new SaveFileDialog();
saveDialog.DefaultExt ="xls";
saveDialog.Filter="Excel文件|*.xls";
saveDialog.FileName =filename;
saveDialog.ShowDialog();
saveFileName=saveDialog.FileName;
if(saveFileName.IndexOf(":")<0) return false; //被点了取消
beforeTime = DateTime.Now;//Excel启动之前时间
Excel.Application xlApp=new Excel.Application();
afterTime = DateTime.Now;//Excel启动之后时间
if(xlApp==null)
MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
return false;
Excel.Workbooks workbooks=xlApp.Workbooks;
Excel.Workbook workbook=workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet worksheet=(Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
Excel.Range range;
long totalCount=dt.Rows.Count;
long rowRead=0;
float percent=0;
//合并单元格
Excel.Range rH = worksheet.get_Range("A1",intToString(dt.Columns.Count)+"1");
rH.Merge(0);
//写如标题
worksheet.Cells[1,1]=excelname;
//标题样式
range=(Excel.Range)worksheet.Cells[1,1];
range.Interior.ColorIndex = 15;
range.Font.Size = 14;
range.Font.Name = "隶书";
range.Font.Bold = true;
range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
//写入字段
for(int i=0;i<dt.Columns.Count;i++)
worksheet.Cells[2,i+1]=dt.Columns[i].ColumnName;
//获取字段样式
range=(Excel.Range)worksheet.Cells[2,i+1];
range.Font.Bold = true;
//写入数值
for(int r=0;r<dt.Rows.Count;r++)
for(int i=0;i<dt.Columns.Count;i++)
worksheet.Cells[r+3,i+1]=dt.Rows[r][i];
rowRead++;
percent=((float)(100*rowRead))/totalCount;
System.Windows.Forms .Application.DoEvents();
range=worksheet.get_Range(worksheet.Cells[2,1],worksheet.Cells[dt.Rows.Count+2,dt.Columns.Count]);
range.BorderAround(Excel.XlLineStyle.xlContinuous,Excel.XlBorderWeight.xlThin,Excel.XlColorIndex.xlColorIndexAutomatic,null);
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle =Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight =Excel.XlBorderWeight.xlThin;
if(dt.Columns.Count>1)
range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex =Excel.XlColorIndex.xlColorIndexAutomatic;
range.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlInsideVertical].Weight = Excel.XlBorderWeight.xlThin;
if(saveFileName!="")
try
workbook.Saved =true;
workbook.SaveCopyAs(saveFileName);
fileSaved=true;
catch(Exception ex)
fileSaved=false;
MessageBox.Show("导出文件时出错,文件可能正被打开!\n"+ex.Message);
else
fileSaved=false;
xlApp.Quit();
GC.Collect();//强行销毁,经测试这句话并没有结束Excel进程
KillExcelProcess();//强制结束进程
//用Excel打开文件
//if(fileSaved&&File.Exists(saveFileName))System.Diagnostics.Process.Start(saveFileName);
return fileSaved;
/// <summary>
/// 数字转字符。如:1转A 2转B
/// </summary>
/// <param name="num">要转换的数字,最大为26,最小为1</param>
/// <returns></returns>
private string intToString(int num)
if (num>26 || num<1)
return null;
string[] str = new string[26];
str[0] = "A";
str[1] = "B";
str[2] = "C";
str[3] = "D";
str[4] = "E";
str[5] = "F";
str[6] = "G";
str[7] = "H";
str[8] = "I";
str[9] = "J";
str[10] = "K";
str[11] = "L";
str[12] = "M";
str[13] = "N";
str[14] = "O";
str[15] = "P";
str[16] = "Q";
str[17] = "R";
str[18] = "S";
str[19] = "T";
str[20] = "U";
str[21] = "V";
str[22] = "W";
str[23] = "S";
str[24] = "Y";
str[25] = "Z";
return str[num-1];
/// <summary>
/// 结束Excel进程
/// </summary>
private void KillExcelProcess()
Process[] myProcesses;
DateTime startTime;
myProcesses = Process.GetProcessesByName("Excel");
//得不到Excel进程ID,暂时只能判断进程启动时间
foreach(Process myProcess in myProcesses)
startTime = myProcess.StartTime;
if(startTime > beforeTime && startTime < afterTime)
myProcess.Kill();
看完别忘记了加分啊! 参考技术A
可以。
C#可以使用 oledb,连接并操作excel,可以使用sql,就像操作数据库一样。
创建连接字符串,主要参数有:data source,provider,Extended properties,HDR,IMEX等等。
provider是你用来连接execl的驱动版本,
data source就是你要连接的excel文件,
例子:connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\\"Excel 12.0;HDR=NO;IMEX=1\\"";
下一步就可以使用这个连接字符串,创建链接对象
objConn = new OleDbConnection(connStr);
然后就可以打开这个连接对象。
objConn.Open();
使用sql语句创建cmd对象
写sql语句时,表名称就是excel表格的sheet名称,
写法举例(以select为例)
select * from [Sheet1$] //sheet的名称写法两边要加上方括号[],表的名称末尾要加上“$”
然后就可以执行cmd命令了。
一、创建一个windows项目,在窗体里面放一个button,和一个dataGridView。
二、在解决方案资源管理器的引用中点击右键->添加引用->.Net->Microsoft.office.Interop.Excel(版本选11.0的不行的话就选12.0的)->确定。下面,继续在解决方案资源管理器的引用中点击右键->添加引用->COM->Microsoft office 11.0 Object Library->确定。
三、添加这两句:
using System.Data.OleDb;
using Microsoft.Office.Interop.Excel;
四、在button的Click事件中写:
//写明excel的路径
string excel_path = "D:\\贫困生综合情况表.xls";
//创建一个数据链接
string strCon = "Provider = Microsoft.Jet.OLEDB.4.0;Data Source =" + excel_path + ";Extended Properties=Excel 8.0";
//Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|Database.accdb
OleDbConnection myConn = new OleDbConnection(strCon);
string strCom = "SELECT * FROM [Sheet1$]";
myConn.Open();
//打开数据链接,得到一个数据集
OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
//创建一个 DataSet对象
DataSet myDataSet = new DataSet();
//得到自己的DataSet对象
myCommand.Fill(myDataSet, "[Sheet1$]");
//关闭此数据链接
myConn.Close();
dataGridView1.DataMember = "[Sheet1$]";
dataGridView1.DataSource = myDataSet;
这样,点击那个button就可以在dataGridView中显示那个excel的路径了
五、要进行筛选的话,先复制下面这个方法进去:
OleDbConnection conn;
OleDbDataAdapter adapter;
public System.Data.DataSet dbconn(string strSql)
conn = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0;Data Source =D:\\贫困生综合情况表.xls;Extended Properties=Excel 8.0");
conn.Open();
this.adapter = new OleDbDataAdapter(strSql, conn);
//System.Data.DataTable dtSelect = new System.Data.DataTable();
//int rnt = this.adapter.Fill(dtSelect);
DataSet myDataSet = new DataSet();
this.adapter.Fill(myDataSet, "[Sheet1$]");
conn.Close();
return myDataSet;
再添加一个button2,在button2的click事件中写:
dataGridView1.DataSource = null;
string Sql = "select * from [Sheet1$] where 1<2";
System.Data.DataSet ds = dbconn(Sql);
dataGridView1.DataMember = "[Sheet1$]";
dataGridView1.DataSource = ds;
这样就能够执行Sql语句所要做的东西了。
不知道我的回答是否符合你的需求,有什么问题可以跟我联系,在我的百度空间上留言,我会继续回复你 参考技术C 连接字符串:"Driver=Microsoft Excel Driver (*.xls);DriverId=790;Dbq=c:\somepath\mySpreadsheet.xls;DefaultDir=c:\somepath "
然后使用ODBC访问数据库:ODBCConnection、ODBCCommand、ODBCDataAdapter等本回答被提问者采纳 参考技术D 使用的
以上是关于C#能不能像操作SQL数据库那样使用sql语句对excel进行读取更新等操作?的主要内容,如果未能解决你的问题,请参考以下文章