C# 文件上传下载(Excel导入,多线程下载)功能的实现代码
废话不多说了,直接给大家贴代码,具体代码如下所示:
//打开Excel文件,转换为DataTable DataTabledtExcel; privatevoidOpenFile() { OpenFileDialogdialog=newOpenFileDialog(); dialog.Filter="MicrosoftExcelfiles(*.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文件,页名称 /// 是否将第一列作为表头 /// privateDataTableExcelToDataTable(stringfileName,stringsheetName,boolisFirstRowColumn) { IWorkbookworkbook=null; FileStreamfs=null; ISheetsheet=null; DataTabledata=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) { IRowfirstRow=sheet.GetRow(0); intcellCount=firstRow.LastCellNum;//一行最后一个cell的编号即总的列数 if(isFirstRowColumn) { for(inti=firstRow.FirstCellNum;i 文件下载:
privatevoidDownLoad() { if(impdefineBM!=null) { FolderBrowserDialogpath=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("."));//注意:下载文件名的命名,可根据实际需求调整调用的文件创建方式 MultiDownloaddownload=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() { HttpWebRequestrequest=(HttpWebRequest)WebRequest.Create(_fileUrl); HttpWebResponseresponse=(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) { StreamhttpFileStream=null,localFileStram=null; try { int[]ran=objasint[]; stringtmpFileBlock=System.IO.Path.GetTempPath()+Thread.CurrentThread.Name+".tmp"; _tempFiles.Add(tmpFileBlock); HttpWebRequesthttprequest=(HttpWebRequest)WebRequest.Create(_fileUrl); httprequest.AddRange(ran[0],ran[1]); HttpWebResponsehttpresponse=(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(Exceptionex) { thrownewException(ex.Message.ToString()); } finally { if(httpFileStream!=null)httpFileStream.Dispose(); if(localFileStram!=null)localFileStram.Dispose(); } if(_threadCompleteNum==_threadNum) { Complete(); _isComplete=true; } } /// ///下载完成后合并文件块 /// privatevoidComplete() { StreammergeFile=null; BinaryWriterAddWriter=null; try { using(mergeFile=newFileStream(@_savePath,FileMode.Create))//根据实际情况调整FileMode { AddWriter=newBinaryWriter(mergeFile); foreach(stringfilein_tempFiles) { using(FileStreamfs=newFileStream(file,FileMode.Open)) { BinaryReaderTempReader=newBinaryReader(fs); AddWriter.Write(TempReader.ReadBytes((int)fs.Length)); TempReader.Close(); } File.Delete(file); } } MyMessageBox.Show("下载完成!"); } catch(Exceptionex) { thrownewException(ex.Message); } finally { if(AddWriter!=null) { AddWriter.Close(); AddWriter.Dispose(); } if(mergeFile!=null) { mergeFile.Close(); mergeFile.Dispose(); } } } }总结
以上所述是小编给大家介绍的C#文件上传下载(Excel导入,多线程下载)功能的实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!