我如何从excel文件中读取

时间:2014-01-18 10:58:19

标签: c# excel list file-io dataset

请你能用我的实际脚本来帮助我。我已经从excel文件中选择了但现在我不知道如何为我的列表增加价值。我不仅从一个文件中获取更多文件中的数据。

这是我的实际脚本:

基本按钮启动事件以供阅读。

private void next_Click(object sender, EventArgs e)
{
    for (int i = 0; i < UniqueValue.traceToFile.Count; i++)
    {
        ReadFromExcel read = new ReadFromExcel();
        read.ReadData(UniqueValue.traceToFile[i]);
    }
}

下一步是:

class ReadFromExcel : Config
{
    public void ReadData(string fullpath)
    {
        DataSet da = new DataSet();
        OleDbDataAdapter adapter = new OleDbDataAdapter();
        string cell = "C7";
        string name = "List1";

        string FileName = fullpath;
        string _ConnectionString = string.Empty;
        string _Extension = Path.GetExtension(FileName);
        // Checking for the extentions, if XLS connect using Jet OleDB
        if (_Extension.Equals(".xls", StringComparison.CurrentCultureIgnoreCase))
        {
            _ConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0};Extended Properties=Excel 8.0", FileName);
        }
        // Use ACE OleDb
        else if (_Extension.Equals(".xlsx", StringComparison.CurrentCultureIgnoreCase))
        {
            _ConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", FileName);
        }

        OleDbConnection con = new OleDbConnection(_ConnectionString);
        string strCmd = "SELECT * FROM [" + name + "$" + cell + "]";
        OleDbCommand cmd = new OleDbCommand(strCmd, con);

        try
        {
            con.Open();
            da.Clear();
            adapter.SelectCommand = cmd;
            adapter.Fill(da);
        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

        finally
        {
            con.Close();
        }
    }
}

现在我需要将此结果写入我的列表。我只从每个文件中读取一个单元格。

结果列表是

public static List<int> money = new List<int>();

我非常感谢所有可以帮助我的答案。

2 个答案:

答案 0 :(得分:0)

我认为以下代码会对您有所帮助。 在这个例子中,dt,dt2和dt3将考虑从函数ReadData函数返回,该函数具有来自excel的数据表。

public static List<int> money = new List<int>();

protected void Page_Load(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    dt.Columns.Add("ID", typeof(Int32));
    dt.Columns.Add("Name");
    dt.Rows.Add();
    dt.Rows[dt.Rows.Count - 1]["ID"] = 1;
    dt.Rows[dt.Rows.Count - 1]["Name"] = "Test1";



    DataTable dt2 = new DataTable();
    dt2.Columns.Add("ID", typeof(Int32));
    dt2.Columns.Add("Name");
    dt2.Rows.Add();
    dt2.Rows[dt2.Rows.Count - 1]["ID"] = 2;
    dt2.Rows[dt2.Rows.Count - 1]["Name"] = "Test2";


    DataTable dt3 = new DataTable();
    dt3.Columns.Add("ID", typeof(Int32));
    dt3.Columns.Add("Name");
    dt3.Rows.Add();
    dt3.Rows[dt3.Rows.Count - 1]["ID"] = 3;
    dt3.Rows[dt3.Rows.Count - 1]["Name"] = "Test2";


    money = (from row in dt.AsEnumerable() select Convert.ToInt32(row["ID"])).ToList();
    money.AddRange((from row in dt2.AsEnumerable() select Convert.ToInt32(row["ID"])).ToList());
    money.AddRange((from row in dt3.AsEnumerable() select Convert.ToInt32(row["ID"])).ToList());
}

答案 1 :(得分:-1)

Excel.Application excel;
Excel.Workbook wb;
Excel.Worksheet sh;

DataTable dt=new DataTable();

excel = new Excel.Application();
excel.Visible = true;
wb = excel.Workbooks.Open("File Path");
sh = wb.Sheets.Add();
sh.Name = "Data";
count = 2;
sh.Cells[count, "A"].Value2 = "Column Name 1";
sh.Cells[count, "B"].Value2 = "Column Name 2";
sh.Cells[count, "C"].Value2 = "Column Name 3";
sh.Cells[count, "D"].Value2 = "Column Name 4";
sh.Cells[count, "E"].Value2 = "Column Name 5";
sh.Range["A" + count + "", "E" + count + ""].Font.Size = 12;
sh.Range["A" + count + "", "E" + count + ""].Borders.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
sh.Range["I2"].WrapText = true;

try
{
    con.Open();
    da.Clear();
    adapter.SelectCommand = cmd;
    adapter.Fill(dt);
    foreach (DataRow row in dt.Rows)
    {
    sh.Cells[count, "A"].Value2 = row["Column Name"].ToString();
    sh.Cells[count, "B"].Value2 = row["Column Name"].ToString();
    sh.Cells[count, "C"].Value2 = row["Column Name"].ToString();
    sh.Cells[count, "D"].Value2 = row["Column Name"].ToString();
    sh.Cells[count, "E"].Value2 = row["Column Name"].ToString();
    }
    wb.SaveAs("File Path" + "File Nmae" + ".xls");
    excel.Workbooks.Close();
    excel.Quit();

}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
}

finally
{
    con.Close();
}