一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

C# 文件上传下载(Excel导入,多线程下载)功能的实现代码

时间:2022-06-25 07:47:57 编辑:袖梨 来源:一聚教程网

//打开Excel文件,转换为DataTable
      DataTable dtExcel;
    privatevoidOpenFile()
    {
      OpenFileDialog dialog =newOpenFileDialog();
      dialog.Filter ="Microsoft Excel files(*.xls)|*.xls;*.xlsx";//筛选打开文件类型 :图片 *.jpg|*.jpg|*.bmp|*.bmp ;"音频文|*.mp3;*.wma;*.aac;*.midi;*.wav" 等等
      if(dialog.ShowDialog() == DialogResult.OK)
      {
        dialogFileName = dialog.FileName;
        dtExcel = ExcelToDataTable(dialogFileName,"sheet1",true);
      }
    }
/// 
  /// Excel转Datatable
  /// 
  /// 文件名含后缀名
  /// Excel文件,页名称
  /// 是否将第一列作为表头
  /// 
  privateDataTable ExcelToDataTable(stringfileName,stringsheetName,boolisFirstRowColumn)
  {
   IWorkbook workbook =null;
   FileStream fs =null;
   ISheet sheet =null;
   DataTable data =newDataTable();
   intstartRow = 0;
   try
   {
    fs =newFileStream(fileName, FileMode.Open, FileAccess.Read);
    if(fileName.IndexOf(".xlsx") > 0)// 2007版本
     workbook =newXSSFWorkbook(fs);
    elseif(fileName.IndexOf(".xls") > 0)// 2003版本
     workbook =newHSSFWorkbook(fs);
    if(sheetName !=null)
    {
     sheet = workbook.GetSheet(sheetName);
     if(sheet ==null)//如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
     {
      sheet = workbook.GetSheetAt(0);
     }
    }
    else
    {
     sheet = workbook.GetSheetAt(0);
    }
    if(sheet !=null)
    {
     IRow firstRow = sheet.GetRow(0);
     intcellCount = firstRow.LastCellNum;//一行最后一个cell的编号 即总的列数
     if(isFirstRowColumn)
     {
      for(inti = firstRow.FirstCellNum; i < cellCount; ++i)
      {
       ICell cell = firstRow.GetCell(i);
       if(cell !=null)
       {
        stringcellValue = cell.StringCellValue;
        if(cellValue !=null)
        {
         DataColumn column =newDataColumn(cellValue);
         data.Columns.Add(column);
        }
       }
      }
      startRow = sheet.FirstRowNum + 1;
     }
     else
     {
      startRow = sheet.FirstRowNum;
     }
     //最后一列的标号
     introwCount = sheet.LastRowNum;
     for(inti = startRow; i <= rowCount; ++i)
     {
      IRow row = sheet.GetRow(i);
      if(row ==null)continue;//没有数据的行默认是null       
      DataRow dataRow = data.NewRow();
      for(intj = row.FirstCellNum; j < cellCount; ++j)
      {
       if(row.GetCell(j) !=null)//同理,没有数据的单元格都默认是null
        dataRow[j] = row.GetCell(j).ToString();
      }
      data.Rows.Add(dataRow);
     }
    }
    returndata;
   }
   catch(Exception ex)
   {
    MyMessageBox.Show(ex.Message);
    returnnull;
   }
  }

文件下载:

privatevoidDownLoad()
  {
   if(impdefineBM !=null)
   {
    FolderBrowserDialog path =newFolderBrowserDialog();
    path.ShowDialog();
    if(path !=null&& path.SelectedPath !="")
    {
     stringurl =@"http://192.168.1.1/XX.xls";  //下载地址
     stringname ="FileName";              // 文件名称
     stringsavefilepath = path.SelectedPath +""+ name + url.Substring(url.LastIndexOf("."));//注意:下载文件名的命名 ,可根据实际需求调整调用的文件创建方式
     MultiDownload download =newMultiDownload(5, url, savefilepath);//调用多线程下载
     download.Start();
    }
   }
  }
 #region 多线程下载
  publicclassMultiDownload
  {
   #region 变量
   privateint_threadNum;   //线程数量
   privatelong_fileSize;   //文件大小
   privatestring_fileUrl;  //文件地址
   privatestring_fileName;  //文件名
   privatestring_savePath;  //保存路径
   privateshort_threadCompleteNum;//线程完成数量
   privatebool_isComplete;  //是否完成
   privatevolatileint_downloadSize;//当前下载大小(实时的)
   privateThread[] _thread;  //线程数组
   privateList _tempFiles =newList();
   privateobjectlocker =newobject();
   #endregion
   #region 属性
   /// 
   /// 文件名
   /// 
   publicstringFileName
   {
    get
    {
     return_fileName;
    }
    set
    {
     _fileName = value;
    }
   }
   /// 
   /// 文件大小
   /// 
   publiclongFileSize
   {
    get
    {
     return_fileSize;
    }
   }
   /// 
   /// 当前下载大小(实时的)
   /// 
   publicintDownloadSize
   {
    get
    {
     return_downloadSize;
    }
   }
   /// 
   /// 是否完成
   /// 
   publicboolIsComplete
   {
    get
    {
     return_isComplete;
    }
   }
   /// 
   /// 线程数量
   /// 
   publicintThreadNum
   {
    get
    {
     return_threadNum;
    }
   }
   /// 
   /// 保存路径
   /// 
   publicstringSavePath
   {
    get
    {
     return_savePath;
    }
    set
    {
     _savePath = value;
    }
   }
   #endregion
   /// 
   /// 构造函数
   /// 
   /// 线程数量
   /// 文件Url路径
   /// 本地保存路径
   publicMultiDownload(intthreahNum,stringfileUrl,stringsavePath)
   {
    this._threadNum = threahNum;
    this._thread =newThread[threahNum];
    this._fileUrl = fileUrl;
    this._savePath = savePath;
   }
   publicvoidStart()
   {
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_fileUrl);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    _fileSize = response.ContentLength;
    intsingelNum = (int)(_fileSize / _threadNum); //平均分配
    intremainder = (int)(_fileSize % _threadNum); //获取剩余的
    request.Abort();
    response.Close();
    for(inti = 0; i < _threadNum; i++)
    {
     List range =newList();
     range.Add(i * singelNum);
     if(remainder != 0 && (_threadNum - 1) == i)//剩余的交给最后一个线程
      range.Add(i * singelNum + singelNum + remainder - 1);
     else
      range.Add(i * singelNum + singelNum - 1);
     //下载指定位置的数据
     int[] ran =newint[] { range[0], range[1] };
     _thread[i] =newThread(newParameterizedThreadStart(Download));
     _thread[i].Name = System.IO.Path.GetFileNameWithoutExtension(_fileUrl) +"_{0}".Replace("{0}", Convert.ToString(i + 1));
     _thread[i].Start(ran);
    }
    //MessageBox.Show("下载完成!");
   }
   privatevoidDownload(objectobj)
   {
    Stream httpFileStream =null, localFileStram =null;
    try
    {
     int[] ran = objasint[];
     stringtmpFileBlock = System.IO.Path.GetTempPath() + Thread.CurrentThread.Name +".tmp";
     _tempFiles.Add(tmpFileBlock);
     HttpWebRequest httprequest = (HttpWebRequest)WebRequest.Create(_fileUrl);
     httprequest.AddRange(ran[0], ran[1]);
     HttpWebResponse httpresponse = (HttpWebResponse)httprequest.GetResponse();
     httpFileStream = httpresponse.GetResponseStream();
     localFileStram =newFileStream(tmpFileBlock, FileMode.Create);
     byte[] by =newbyte[5000];
     intgetByteSize = httpFileStream.Read(by, 0, (int)by.Length);//Read方法将返回读入by变量中的总字节数
     while(getByteSize > 0)
     {
      Thread.Sleep(20);
      lock(locker) _downloadSize += getByteSize;
      localFileStram.Write(by, 0, getByteSize);
      getByteSize = httpFileStream.Read(by, 0, (int)by.Length);
     }
     lock(locker) _threadCompleteNum++;
    }
    catch(Exception ex)
    {
     thrownewException(ex.Message.ToString());
    }
    finally
    {
     if(httpFileStream !=null) httpFileStream.Dispose();
     if(localFileStram !=null) localFileStram.Dispose();
    }
    if(_threadCompleteNum == _threadNum)
    {
     Complete();
     _isComplete =true;
    }
   }
   /// 
   /// 下载完成后合并文件块
   /// 
   privatevoidComplete()
   {
    Stream mergeFile =null;
    BinaryWriter AddWriter =null;
    try
    {
     using(mergeFile =newFileStream(@_savePath, FileMode.Create))//根据实际情况调整FileMode
     {
      AddWriter =newBinaryWriter(mergeFile);
      foreach(stringfilein_tempFiles)
      {
       using(FileStream fs =newFileStream(file, FileMode.Open))
       {
        BinaryReader TempReader =newBinaryReader(fs);
        AddWriter.Write(TempReader.ReadBytes((int)fs.Length));
        TempReader.Close();
       }
       File.Delete(file);
      }
     }
     MyMessageBox.Show("下载完成!");
    }
    catch(Exception ex)
    {
     thrownewException(ex.Message);
    }
    finally
    {
     if(AddWriter !=null)
     {
      AddWriter.Close();
      AddWriter.Dispose();
     }
     if(mergeFile !=null)
     {
      mergeFile.Close();
      mergeFile.Dispose();
     }
    }
   }
  }


热门栏目