我正在制作一个将两个数据库合并在一起的程序....我可以使用以下代码将Excel电子表格导入DataGridView:
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\test.xls;Extended Properties=""Excel 8.0;HDR=YES;IMEX=1""";
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
DbDataAdapter adapter = factory.CreateDataAdapter();
DbCommand selectCommand = factory.CreateCommand();
selectCommand.CommandText = "SELECT * FROM [All Carpets to Excel$]";
DbConnection connection = factory.CreateConnection();
connection.ConnectionString = connectionString;
selectCommand.Connection = connection;
adapter.SelectCommand = selectCommand;
data = new DataSet();
adapter.Fill(data);
dataGridView1.DataSource = data.Tables[0].DefaultView;
我遇到的问题是我正在尝试找到一种方法将源文件更改为对话框返回的路径。我有一个包含文件路径的字符串文件。如何将其合并到连接字符串中?
或许还有一种更好的方法可以做到这一点?
谢谢!
路
答案 0 :(得分:2)
使用OleDbConnectionStringBuilder
类修改连接字符串。
string fileName = "your path to the excel.xls"; // From the dialog box.
OleDbConnectionStringBuilder connStringBuilder =
new OleDbConnectionStringBuilder();
connStringBuilder.DataSource = fileName; // Set path to excel file
connStringBuilder.Provider = "Microsoft.Jet.OLEDB.4.0";
connStringBuilder.Add("Extended Properties", "Excel 8.0;HDR=YES;IMEX1");
...
// Get the connection string from the builder.
connection.ConnectionString = connStringBuilder.ConnectionString;
答案 1 :(得分:0)
您只需要Microsoft.Office.Interop.Excel并将其与数据表和数据集结合使用。
Excel.Workbook ExWorkbook;
Excel.Worksheet ExWorksheet;
Excel.Range ExRange;
Excel.Application ExObj = new Excel.Application();
DataTable dt = new DataTable("dataTable");
DataSet dsSource = new DataSet("dataSet");
dt.Reset();
openFileDialog1.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
ExWorkbook = ExObj.Workbooks.Open(openFileDialog1.FileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
ExWorksheet = (Excel.Worksheet)ExWorkbook.Sheets.get_Item(1);
ExRange = ExWorksheet.UsedRange;
for (int Cnum = 1; Cnum <= ExRange.Columns.Count; Cnum++)
{
dt.Columns.Add(new DataColumn((ExRange.Cells[1, Cnum] as Excel.Range).Value2.ToString()));
}
dt.AcceptChanges();
string[] columnNames = new String[dt.Columns.Count];
for (int i = 0; i < dt.Columns.Count; i++)
{
columnNames[0] = dt.Columns[i].ColumnName;
}
for (int Rnum = 2; Rnum <= ExRange.Rows.Count; Rnum++)
{
DataRow dr = dt.NewRow();
for (int Cnum = 1; Cnum <= ExRange.Columns.Count; Cnum++)
{
if ((ExRange.Cells[Rnum, Cnum] as Excel.Range).Value2 != null)
{
dr[Cnum - 1] = (ExRange.Cells[Rnum, Cnum] as Excel.Range).Value2.ToString();
}
}
dt.Rows.Add(dr);
dt.AcceptChanges();
}
ExWorkbook.Close(true, Missing.Value, Missing.Value);
ExObj.Quit();
dataGridView1.DataSource = dt;