码迷,mamicode.com
首页 > 其他好文 > 详细

读写Excel

时间:2016-06-22 10:50:44      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:

     public string ShiPin()
        {
            //获取项目下的目录
            string filePath = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "视频.xls";

            //根据路径读取Excel,装进DataTable里
            System.Data.DataTable table = GetTableFromExcel("sheet1", filePath);

            //克隆 System.Data.DataTable 的结构,包括所有 System.Data.DataTable 架构和约束。(为了抓异常数据)
            System.Data.DataTable table200 = table.Clone();

            //清除数据
            table200.Clear();

            //视频路径
            string fileFullName = string.Empty;

            //根据条件查询Excel里列名为用户ID = user_id的第一条数据
            //DataRow dr = table.Select(string.Format("用户ID = ‘{0}‘", user_id)).First();

            if (table != null && table.Rows.Count > 0)
            {
                for (int i = 0; i < table.Rows.Count; ++i)
                {
                    //获取第i+1行的Excel数据
                    DataRow dateRow = table.Rows[i];
                    //获取视频路径,例:www.baidu.com/Files/1.f4v 或wmv格式
                    string path = dateRow["RESOURSE_URL"].ToString();
                    if (!string.IsNullOrEmpty(path))
                    {
                        //获取本地视频路径
                        fileFullName = path.Replace("www.baidu.com/Files", "F:/视频").Replace(".f4v", ".mp4").Replace(".wmv", ".mp4");
                        //判断视频是否存在
                        if (System.IO.File.Exists(fileFullName))
                        {
                            //读取视频
                            FileStream fs = new FileStream(fileFullName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                            //判断视频大于200M
                            if (fs.Length > 209715200)
                            {
                                string destPath = Path.Combine(@"E:\视频", Path.GetFileName(fileFullName));
                   //复制原有视频,到新的目录下 System.IO.File.Copy(fileFullName, destPath,
true); table200.ImportRow(dateRow); } else { byte[] str2 = new byte[fs.Length]; fs.Read(str2, 0, str2.Length); fs.Close(); fs.Dispose(); //上传视频(未写) } } } //回收 GC.Collect(); } } //如果有异常数据,则将异常数据输出到dayu200文件夹的1.xls里 if (table200 != null && table200.Rows.Count > 0) { DataTabletoExcel(table200, AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "dayu200/1.xls"); } return ""; } /// <summary> /// 获取Excel内容。 /// </summary> /// <param name="sheetName">工作表名称,例:sheet1</param> /// <param name="filePath">Excel路径</param> /// <returns></returns> private DataTable GetTableFromExcel(string sheetName, string filePath) { const string connStrTemplate = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;"; DataTable dt = null; if (!System.IO.File.Exists(filePath)) { // don‘t find file return null; } OleDbConnection conn = new OleDbConnection(string.Format(connStrTemplate, filePath)); try { conn.Open(); if (sheetName == null || sheetName.Trim().Length == 0) { DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); sheetName = schemaTable.Rows[0]["TABLE_NAME"].ToString().Trim(); } else { sheetName += "$"; } string strSQL = "Select * From [" + sheetName + "]"; OleDbDataAdapter da = new OleDbDataAdapter(strSQL, conn); DataSet ds = new DataSet(); da.Fill(ds); dt = ds.Tables[0]; } catch (Exception ex) { throw ex; } finally { conn.Close(); } return dt; } /// <summary> /// 将DataTable的数据写进Excel里 /// </summary> /// <param name="tmpDataTable">DataTable数据</param> /// <param name="strFileName">Excel路径</param> public static void DataTabletoExcel(System.Data.DataTable tmpDataTable, string strFileName) { if (tmpDataTable == null) { return; } int rowNum = tmpDataTable.Rows.Count; int columnNum = tmpDataTable.Columns.Count; int rowIndex = 1; int columnIndex = 0; //需要引用Microsoft.Office.Interop.Excel.dll Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass(); xlApp.DefaultFilePath = ""; xlApp.DisplayAlerts = true; xlApp.SheetsInNewWorkbook = 1; Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true); //将DataTable的列名导入Excel表第一行 foreach (DataColumn dc in tmpDataTable.Columns) { columnIndex++; xlApp.Cells[rowIndex, columnIndex] = dc.ColumnName; } //将DataTable中的数据导入Excel中 for (int i = 0; i < rowNum; i++) { rowIndex++; columnIndex = 0; for (int j = 0; j < columnNum; j++) { columnIndex++; xlApp.Cells[rowIndex, columnIndex] = tmpDataTable.Rows[i][j].ToString(); } } //xlBook.SaveCopyAs(HttpUtility.UrlDecode(strFileName, System.Text.Encoding.UTF8)); xlBook.SaveCopyAs(strFileName); }

 

读写Excel

标签:

原文地址:http://www.cnblogs.com/cang12138/p/5606130.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!