正在构建一个将excel数据导入到sql数据库中的应用程序,但无法从具有不同于通常文件名的excel表中导入excel数据的
Sheet1,Sheet2,Sheet *
所以我想我会尝试从组合框中读取工作表名称,但无法从私有方法访问在公共方法中声明的变量。
public void OpenFile()
{
OpenFileDialog od = new OpenFileDialog();
od.Filter = "Excell|*.xls;*.xlsx;";
DialogResult dr = od.ShowDialog();
if (dr == DialogResult.Abort)
return;
if (dr == DialogResult.Cancel)
return;
if (!string.IsNullOrEmpty(od.FileName))
{
//This is the variable am trying to access
string file = od.FileName.ToString();
OleDbcon = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + od.FileName + ";Extended Properties=Excel 12.0;");
OleDbcon.Open();
DataTable dt = OleDbcon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
OleDbcon.Close();
cbosheet.Items.Clear();
for (int i = 0; i < dt.Rows.Count; i++)
{
String sheetName = dt.Rows[i]["TABLE_NAME"].ToString();
sheetName = sheetName.Replace(@"'", "");
sheetName = sheetName.Replace("$", "");
cbosheet.Items.Add(sheetName);
}
}
}
正在尝试在此方法中使用变量 file
private void toolStripButton4_Click(object sender, EventArgs e)
{
bulkcopy(text);
}
将在此处使用
public void bulkcopy(string excelFilePath)
{
string ssqltable = "Member";
string myexceldataquery = "select [Employer Number],[Employer Name],[CODE],[No_of Employees],[VALUE],[Last month contributed for] from [" + cbosheet.Text + "$]";
try
{
string excelconn = @"provider=microsoft.ACE.OLEDB.12.0;data source=" + excelFilePath +
";extended properties=" + "\"excel 12.0;hdr=yes;\"";
...
答案 0 :(得分:0)
为文件设置public
属性:
public string CurrentFile { get; set; }
然后在您的代码中:
//This is the variable am trying to access
CurrentFile = od.FileName.ToString();
和:
private void toolStripButton4_Click(object sender, EventArgs e)
{
bulkcopy(CurrentFile);
}