操作EXCEL数据

string filePath = @"F:\Tim\UpdatePIMData1\Staff.xls";

private DataSet SearchDataSource()
{
string strCon;
strCon
= "Provider=Microsoft.Jet.Oledb.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
OleDbConnection olecon
= new OleDbConnection(strCon);
OleDbDataAdapter myda
= new OleDbDataAdapter("SELECT StaffID,JoinDate FROM [Staff$]", olecon);

DataSet myds
= new DataSet();
myda.Fill(myds);
return myds;
}

  

/// <summary>
/// 写入Excel文档
/// </summary>
/// <param name="Path">文件名称</param>
public bool SaveFP2toExcel(string Path)
{
try
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source="+ Path +";"+"Extended Properties=Excel 8.0;";
OleDbConnection conn
= new OleDbConnection(strConn);
conn.Open();
System.Data.OleDb.OleDbCommand cmd
=new OleDbCommand ();
cmd.Connection
=conn;
//cmd.CommandText ="UPDATE [sheet1$] SET 姓名='2005-01-01' WHERE 工号='日期'";
//cmd.ExecuteNonQuery ();
for(int i=0;i<fp2.Sheets [0].RowCount -1;i++)
{
if(fp2.Sheets [0].Cells[i,0].Text!="")
{
cmd.CommandText
="INSERT INTO [sheet1$] (工号,姓名,部门,职务,日期,时间) VALUES('"+fp2.Sheets [0].Cells[i,0].Text+ "','"+
fp2.Sheets [
0].Cells[i,1].Text+"','"+fp2.Sheets [0].Cells[i,2].Text+"','"+fp2.Sheets [0].Cells[i,3].Text+
"','"+fp2.Sheets [0].Cells[i,4].Text+"','"+fp2.Sheets [0].Cells[i,5].Text+"')";
cmd.ExecuteNonQuery ();
}
}
conn.Close ();
return true;
}
catch(System.Data.OleDb.OleDbException ex)
{
System.Diagnostics.Debug.WriteLine (
"写入Excel发生错误:"+ex.Message );
}
return false;
}

  

protected void DoOleSql(string sql, string database)
{
OleDbConnection conn
= new OleDbConnection();
conn.ConnectionString
= "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ Server.MapPath("\\") + database
+ "; Extended Properties='Excel 8.0;HDR=no;IMEX=0'";
try
{
//打开连接
conn.Open();
}
catch (Exception e)
{
Response.Write(e.ToString());
}
OleDbCommand olecommand
= new OleDbCommand(sql, conn);
try
{
//执行语句
olecommand.ExecuteNonQuery();
}
catch (Exception eee)
{
Response.Write(eee.ToString());

conn.Close();
}
finally
{
conn.Close();
//关闭数据库
}
conn.Close();
}

3、从excel文件读取数据

string  sql  =   " select * from [sheet1$] " ;

DoOleSql(sql,
" test.xls " );

4、更新excel文件中的数据

 

string  sql  =   " update [sheet1$] set FieldName1='333' where FieldName2='b3' " ;

DoOleSql(sql,
" test.xls " );

 

5、向excel文件插入数据

string  sql  =   " insert into [sheet1$](FieldName1,FieldName2,…) values('a',’b’,…) " ;

DoOleSql(sql,
" test.xls " );

6、删除excel文件中的数据:不提倡使用这种方法

7、对于非标准结构的excel表格,可以指定excel中sheet的范围

1)读取数据:string sql = "select * from [sheet1$A3:F20]";

2)更新数据:string sql = "update [sheet1$A9:F15] set FieldName='333' where AnotherFieldName='b3'";

3)插入数据:string sql = "insert into [sheet1$A9:F15](FieldName1,FieldName2,…) values('a',’b’,…)";

4)删除数据:不提倡

注:1)代码根据需要可以自行修改;2)如果出现“操作必须使用一个可更新的查询”错误,可能sql语句中对excel文件中的“字段”引用有错误,或对excel文件不具有“修改”权限;3)如果出现“不能扩充选定范围”错误,可能是对excel文件引用的“范围”有错误。

public static bool SaveDataTableToExcel(System.Data.DataTable excelTable, string filePath)  
{
Microsoft.Office.Interop.Excel.Application app
=
new Microsoft.Office.Interop.Excel.ApplicationClass();
try
{
app.Visible
= false;
Workbook wBook
= app.Workbooks.Add(true);
Worksheet wSheet
= wBook.Worksheets[1] as Worksheet;
if (excelTable.Rows.Count > 0)
{
int row = 0;
row
= excelTable.Rows.Count;
int col = excelTable.Columns.Count;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
string str = excelTable.Rows[i][j].ToString();
wSheet.Cells[i
+ 2, j + 1] = str;
}
}
}

int size = excelTable.Columns.Count;
for (int i = 0; i < size; i++)
{
wSheet.Cells[
1, 1 + i] = excelTable.Columns[i].ColumnName;
}
//设置禁止弹出保存和覆盖的询问提示框
app.DisplayAlerts = false;
app.AlertBeforeOverwriting
= false;
//保存工作簿
wBook.Save();
//保存excel文件
app.Save(filePath);
app.SaveWorkspace(filePath);
app.Quit();
app
= null;
return true;
}
catch (Exception err)
{
MessageBox.Show(
"导出Excel出错!错误原因:" + err.Message, "提示信息",
MessageBoxButtons.OK, MessageBoxIcon.Information);
return false;
}
finally
{
}
}

  

你可能感兴趣的:(Excel)