c#如何使用Microsoft.Office.Interop.Excel库将excel第一张表的指定内容导入到oracle数据库中
时间: 2025-02-03 14:01:43 浏览: 38
要在C#中使用Microsoft.Office.Interop.Excel库将Excel第一张表的指定内容导入到Oracle数据库中,可以按照以下步骤进行:
1. **安装必要的库**:
- 通过NuGet安装`Microsoft.Office.Interop.Excel`。
- 通过NuGet安装`Oracle.ManagedDataAccess.Client`。
2. **编写代码**:
```csharp
using System;
using System.Data;
using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;
using Oracle.ManagedDataAccess.Client;
namespace ExcelToOracle
{
class Program
{
static void Main(string[] args)
{
// Excel文件路径
string excelPath = @"C:\Path\To\Your\ExcelFile.xlsx";
// Oracle数据库连接字符串
string connectionString = "User Id=your_username;Password=your_password;Data Source=your_data_source";
// 创建Excel应用实例
Excel.Application excelApp = new Excel.Application();
Excel.Workbook workbook = excelApp.Workbooks.Open(excelPath);
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Sheets[1]; // 第一张表
Excel.Range usedRange = worksheet.UsedRange;
// 连接数据到DataTable
DataTable dataTable = new DataTable();
int rowCount = usedRange.Rows.Count;
int colCount = usedRange.Columns.Count;
for (int i = 1; i <= colCount; i++)
{
dataTable.Columns.Add((string)(usedRange.Cells[1, i] as Excel.Range).Value2);
}
for (int i = 2; i <= rowCount; i++)
{
DataRow row = dataTable.NewRow();
for (int j = 1; j <= colCount; j++)
{
row[j - 1] = (usedRange.Cells[i, j] as Excel.Range).Value2;
}
dataTable.Rows.Add(row);
}
// 关闭Excel应用
workbook.Close();
excelApp.Quit();
// 导入数据到Oracle数据库
using (OracleConnection connection = new OracleConnection(connectionString))
{
connection.Open();
using (OracleCommand command = connection.CreateCommand())
{
// 假设目标表名为YourTable,列名与Excel列名一致
string insertQuery = "INSERT INTO YourTable (Column1, Column2, Column3) VALUES (:Column1, :Column2, :Column3)";
command.CommandText = insertQuery;
command.CommandType = CommandType.Text;
foreach (DataRow row in dataTable.Rows)
{
command.Parameters.Clear();
command.Parameters.Add(new OracleParameter("Column1", row["Column1"]));
command.Parameters.Add(new OracleParameter("Column2", row["Column2"]));
command.Parameters.Add(new OracleParameter("Column3", row["Column3"]));
command.ExecuteNonQuery();
}
}
}
Console.WriteLine("导入完成");
}
}
}
```
### 说明:
1. **引用命名空间**:引用了`Microsoft.Office.Interop.Excel`和`Oracle.ManagedDataAccess.Client`。
2. **创建Excel应用实例**:使用`Microsoft.Office.Interop.Excel`库打开Excel文件并读取数据。
3. **读取Excel数据**:将Excel数据读取到`DataTable`中。
4. **导入数据到Oracle**:使用`Oracle.ManagedDataAccess.Client`库将`DataTable`中的数据插入到Oracle数据库中。
阅读全文
相关推荐

















