在C#中我想使用Microsoft.Office.Interop.Excel.dll来实现导入功能,但是选择导入文件时可以选择路径
时间: 2024-03-13 15:42:41 浏览: 130
好的,你可以使用以下代码来选择Excel文件的路径,然后使用Microsoft.Office.Interop.Excel.dll来读取Excel文件中的数据,最后将数据导入到数据库中:
```
// 引用 Microsoft.Office.Interop.Excel.dll
using Microsoft.Office.Interop.Excel;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
// 选择Excel文件的路径
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string filePath = openFileDialog1.FileName;
// 使用 Microsoft.Office.Interop.Excel.dll 读取 Excel 文件
Application excelApp = new Application();
Workbook workbook = excelApp.Workbooks.Open(filePath);
Worksheet worksheet = workbook.Sheets[1];
Range range = worksheet.UsedRange;
// 将 Excel 中的数据导入到数据库中
SqlConnection con = new SqlConnection("your connection string");
con.Open();
SqlCommand cmd;
for (int row = 2; row <= range.Rows.Count; row++)
{
cmd = new SqlCommand("INSERT INTO your_table_name (column1, column2, column3) VALUES (@value1, @value2, @value3)", con);
cmd.Parameters.AddWithValue("@value1", (range.Cells[row, 1] as Range).Value2.ToString());
cmd.Parameters.AddWithValue("@value2", (range.Cells[row, 2] as Range).Value2.ToString());
cmd.Parameters.AddWithValue("@value3", (range.Cells[row, 3] as Range).Value2.ToString());
cmd.ExecuteNonQuery();
}
con.Close();
}
```
在上面的代码中,你需要根据你的实际需求修改连接字符串和插入语句中的表名和列名。
阅读全文