C#操作excel(多种方法比较)
2010-09-30 22:37:59 来源:WEB开发网我们在做excel资料的时候,通常有以下方法。
一.导入导出excel常用方法:
1.用查询表的方式查询并show在数据集控件上。
public static string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =C:\\08.xls;Extended Properties=Excel 8.0";
public static DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection(strCon);
string sql = "select * from [Sheet1$]";
conn.Open();
OleDbDataAdapter myCommand = new OleDbDataAdapter(sql, strCon);
ds = new DataSet();
myCommand.Fill(ds, "[Sheet1$]");
conn.Close();
datagrid1.DataMember = "[Sheet1$]";
datagrid1.DataSource = ds;
datagrid1.DataBind();
//Excel.Application excel = new Excel.Application();
//excel.Application.Workbooks.Add(true);
//excel.Visible = true;
}
2.一个一个单元格的进行插入
1 string str = @"Data Source=IT-428E4EA4B0C7\SQLEXPRESS;Initial Catalog=TestBase;Integrated Security=True";
2 SqlConnection conn = new SqlConnection(str);
3 conn.Open();
4 int n = 0;
5 for (int i = 1; i < 20; i++)
6 {
7 if (n > 3)
8 break;
9 else
10 if (msheet.Cells.get_Range("A" + i, Type.Missing).Text.ToString() == "" && n <= 3)
11 { n++; }
12 else
13 {
14 //循环获取excel单元格的值一次一次的插入,excuteSql为执行的存储过程
15 excuteSql(msheet.Cells.get_Range("B" + i, Type.Missing).Text.ToString(),
16 msheet.Cells.get_Range("B" + (i + 1), Type.Missing).Text.ToString(),
17 msheet.Cells.get_Range("B" + (i + 2), Type.Missing).Text.ToString(),
18 conn);
19 i = i + 3;
20
21 }
22 }
23
24 conn.Close();
更多精彩
赞助商链接