菜鸟求教,C# 读取excel文件的问题,

wz654273122 2013-03-14 08:50:11
OpenFileDialog opend = new OpenFileDialog();
opend.InitialDirectory = Environment.GetFolderpath(Environment.SpecialFolder.Personal);
opend.Filter = "excel2003(*.xls)|*.xls|excel2003(*.xlsx)|*.xlsx|(*.*)|*.*";//
if (opend.ShowDialog() == DialogResult.OK)
{
filename = opend.FileName;

}

Excel.Application excel = null;
Excel.Workbooks wbs = null;
Excel.Workbook wb = null;
Excel.Worksheet ws = null;
Excel.Range range1 = null;
object Nothing = System.Reflection.Missing.Value;

try
{
excel = new Excel.Application();
excel.UserControl = true;
excel.DisplayAlerts = false;

excel.Application.Workbooks.Open(filename, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing);
excel.Application.Workbooks.Add(true);//zj

wbs = excel.Workbooks;
wb = wbs[1];
ws = (Excel.Worksheet)wb.Worksheets["Sheet2"];

int rowCount = ws.UsedRange.Rows.Count;
int colCount = ws.UsedRange.Columns.Count;

for (int i = 0; i < 3; i++)//
{
object[] row = new object[4];
for (int j = 0; j < 4; j++)
{
range1 = ws.get_Range(ws.Cells[i + 2, j + 1],
ws.Cells[i + 2, j + 1]);
}


}
}
finally
{
if (excel != null)
{
if (wbs != null)
{
if (wb != null)
{
if (ws != null)
{
if (range1 != null)
{
System.Runtime.InteropServices.Marshal.
ReleaseComObject(range1);
range1 = null;
}
System.Runtime.InteropServices.Marshal.
ReleaseComObject(ws);
ws = null;
}
wb.Close(false, Nothing, Nothing);
System.Runtime.InteropServices.Marshal.
ReleaseComObject(wb);
wb = null;
}
wbs.Close();
System.Runtime.InteropServices.Marshal.
ReleaseComObject(wbs);
wbs = null;
}
excel.Application.Workbooks.Close();
excel.Quit();
System.Runtime.InteropServices.Marshal.
ReleaseComObject(excel);
excel = null;
GC.Collect();
}
}

上面是本人仿照写的一段从excel读数据存到数据库的代码。
1》其中红色代码,应该是循环读数据,能解释下循环变量i和j控制什么的吗?get_rang是取什么?
for (int i = 0; i < 3; i++)//
{
object[] row = new object[4];
for (int j = 0; j < 4; j++)
{
range1 = ws.get_Range(ws.Cells[i + 2, j + 1],
ws.Cells[i + 2, j + 1]);
}


}
2》读取的数据怎么存到dataset里面去?
3》怎么读excel的数据?
...全文
85 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
Trust-Me 2013-03-14
  • 打赏
  • 举报
回复


 /// <summary>
    /// 确定
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnFileUp_Click(object sender, EventArgs e)
    {
        string xlsName = "";
        try
        {
            //InputDataBLL input = new InputDataBLL();

           
            if (this.FileUpload1.HasFile)
            {
                string IsXls = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
                
                if (IsXls != ".xls")
                {
                    MessageBox.Show("本程序只能识别excel文件!",this);
                    return;
                }
                xlsName =  DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss")+System.IO.Path.GetFileName(FileUpload1.FileName) ;

                // string filename = this.FileUpload1.PostedFile.FileName.ToString().Trim();

                DataTable dt = new DataTable();
                int len = this.FileUpload1.FileName.ToString().Trim().Length;

                string path = Server.MapPath("../UpLoad/") + xlsName;
                this.FileUpload1.SaveAs(path); //上传文件

                //将上传的Excel文件数据读取出来
                dt = this.InputExcel(xlsName, this.FileUpload1.FileName.ToString().Trim().Substring(0, len - 4), "");
                
                //if (Session["inputdt"] != null)
                //    Session.Remove("inputdt");
                //Session.Add("inputdt", inputdt);
                
                if (dt.Rows.Count > 0)
                {
                    this.GridView1.DataSource = dt;
                    this.GridView1.DataBind();
                }
            }
            else
                throw new Exception("请选择导入表的路径");
        }
        catch (Exception ex)
        {
            Response.Write("<script language='javascript'>alert('" + ex.Message + "');</script>");
        }
    }


    /// <summary>
    /// 导入数据到数据集中
    /// </summary>
    /// <param name="Path"></param>
    /// <param name="TableName"></param>
    /// <param name="tablename2">如果这个有就以他为表名,没有的话就以TableName</param>
    /// <returns></returns>
    public DataTable InputExcel(string xlsName, string TableName, string tablename2)
    {
        try
        {
            //获取到上传的Excel
            string ThePath = Server.MapPath("../") + "UpLoad\\" + xlsName;
            
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + ThePath + ";" + "Extended Properties=Excel 8.0;";
            
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            
            string strExcel = "";
            
            OleDbDataAdapter myCommand = null;

            if (tablename2.Length > 0 && !tablename2.Equals(string.Empty))
            {
                TableName = tablename2;
            }
                

            strExcel = "select * from [" + TableName + "$]";

            myCommand = new OleDbDataAdapter(strExcel, strConn);
            DataTable dt = new DataTable();
            myCommand.Fill(dt);

            conn.Close();
            return dt;

        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }
友情提示,win2003 x64 版IIS不支持 Jet.OLEDB.4.0;
wz654273122 2013-03-14
  • 打赏
  • 举报
回复
在线等高手解答
wz654273122 2013-03-14
  • 打赏
  • 举报
回复
没大侠指教一下吗

110,539

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧