C# 文件上傳下載(Excel導(dǎo)入,多線程下載)功能的實(shí)現(xiàn)代碼
廢話不多說(shuō)了,直接給大家貼代碼,具體代碼如下所示:
//打開(kāi)Excel文件,轉(zhuǎn)換為DataTable
DataTable dtExcel;
private void OpenFile()
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Microsoft Excel files(*.xls)|*.xls;*.xlsx"; //篩選打開(kāi)文件類型 :圖片 *.jpg|*.jpg|*.bmp|*.bmp ;"音頻文|*.mp3;*.wma;*.aac;*.midi;*.wav" 等等
if (dialog.ShowDialog() == DialogResult.OK)
{
dialogFileName = dialog.FileName;
dtExcel = ExcelToDataTable(dialogFileName, "sheet1", true);
}
}
/// <summary>
/// Excel轉(zhuǎn)Datatable
/// </summary>
/// <param name="fileName">文件名含后綴名</param>
/// <param name="sheetName">Excel文件,頁(yè)名稱</param>
/// <param name="isFirstRowColumn">是否將第一列作為表頭</param>
/// <returns></returns>
private DataTable ExcelToDataTable(string fileName, string sheetName, bool isFirstRowColumn)
{
IWorkbook workbook = null;
FileStream fs = null;
ISheet sheet = null;
DataTable data = new DataTable();
int startRow = 0;
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);
if (sheetName != null)
{
sheet = workbook.GetSheet(sheetName);
if (sheet == null) //如果沒(méi)有找到指定的sheetName對(duì)應(yīng)的sheet,則嘗試獲取第一個(gè)sheet
{
sheet = workbook.GetSheetAt(0);
}
}
else
{
sheet = workbook.GetSheetAt(0);
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum; //一行最后一個(gè)cell的編號(hào) 即總的列數(shù)
if (isFirstRowColumn)
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.StringCellValue;
if (cellValue != null)
{
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
}
}
}
startRow = sheet.FirstRowNum + 1;
}
else
{
startRow = sheet.FirstRowNum;
}
//最后一列的標(biāo)號(hào)
int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue; //沒(méi)有數(shù)據(jù)的行默認(rèn)是null
DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
if (row.GetCell(j) != null) //同理,沒(méi)有數(shù)據(jù)的單元格都默認(rèn)是null
dataRow[j] = row.GetCell(j).ToString();
}
data.Rows.Add(dataRow);
}
}
return data;
}
catch (Exception ex)
{
MyMessageBox.Show(ex.Message);
return null;
}
}
文件下載:
private void DownLoad()
{
if (impdefineBM != null)
{
FolderBrowserDialog path = new FolderBrowserDialog();
path.ShowDialog();
if (path != null && path.SelectedPath != "")
{
string url = @"http://192.168.1.1/XX.xls"; //下載地址
string name = "FileName"; // 文件名稱
string savefilepath = path.SelectedPath + "\\" + name + url.Substring(url.LastIndexOf(".")); //注意:下載文件名的命名 ,可根據(jù)實(shí)際需求調(diào)整調(diào)用的文件創(chuàng)建方式
MultiDownload download = new MultiDownload(5, url, savefilepath); //調(diào)用多線程下載
download.Start();
}
}
}
#region 多線程下載
public class MultiDownload
{
#region 變量
private int _threadNum; //線程數(shù)量
private long _fileSize; //文件大小
private string _fileUrl; //文件地址
private string _fileName; //文件名
private string _savePath; //保存路徑
private short _threadCompleteNum; //線程完成數(shù)量
private bool _isComplete; //是否完成
private volatile int _downloadSize; //當(dāng)前下載大小(實(shí)時(shí)的)
private Thread[] _thread; //線程數(shù)組
private List<string> _tempFiles = new List<string>();
private object locker = new object();
#endregion
#region 屬性
/// <summary>
/// 文件名
/// </summary>
public string FileName
{
get
{
return _fileName;
}
set
{
_fileName = value;
}
}
/// <summary>
/// 文件大小
/// </summary>
public long FileSize
{
get
{
return _fileSize;
}
}
/// <summary>
/// 當(dāng)前下載大小(實(shí)時(shí)的)
/// </summary>
public int DownloadSize
{
get
{
return _downloadSize;
}
}
/// <summary>
/// 是否完成
/// </summary>
public bool IsComplete
{
get
{
return _isComplete;
}
}
/// <summary>
/// 線程數(shù)量
/// </summary>
public int ThreadNum
{
get
{
return _threadNum;
}
}
/// <summary>
/// 保存路徑
/// </summary>
public string SavePath
{
get
{
return _savePath;
}
set
{
_savePath = value;
}
}
#endregion
/// <summary>
/// 構(gòu)造函數(shù)
/// </summary>
/// <param name="threahNum">線程數(shù)量</param>
/// <param name="fileUrl">文件Url路徑</param>
/// <param name="savePath">本地保存路徑</param>
public MultiDownload(int threahNum, string fileUrl, string savePath)
{
this._threadNum = threahNum;
this._thread = new Thread[threahNum];
this._fileUrl = fileUrl;
this._savePath = savePath;
}
public void Start()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_fileUrl);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
_fileSize = response.ContentLength;
int singelNum = (int)(_fileSize / _threadNum); //平均分配
int remainder = (int)(_fileSize % _threadNum); //獲取剩余的
request.Abort();
response.Close();
for (int i = 0; i < _threadNum; i++)
{
List<int> range = new List<int>();
range.Add(i * singelNum);
if (remainder != 0 && (_threadNum - 1) == i) //剩余的交給最后一個(gè)線程
range.Add(i * singelNum + singelNum + remainder - 1);
else
range.Add(i * singelNum + singelNum - 1);
//下載指定位置的數(shù)據(jù)
int[] ran = new int[] { range[0], range[1] };
_thread[i] = new Thread(new ParameterizedThreadStart(Download));
_thread[i].Name = System.IO.Path.GetFileNameWithoutExtension(_fileUrl) + "_{0}".Replace("{0}", Convert.ToString(i + 1));
_thread[i].Start(ran);
}
//MessageBox.Show("下載完成!");
}
private void Download(object obj)
{
Stream httpFileStream = null, localFileStram = null;
try
{
int[] ran = obj as int[];
string tmpFileBlock = 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 = new FileStream(tmpFileBlock, FileMode.Create);
byte[] by = new byte[5000];
int getByteSize = httpFileStream.Read(by, 0, (int)by.Length); //Read方法將返回讀入by變量中的總字節(jié)數(shù)
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)
{
throw new Exception(ex.Message.ToString());
}
finally
{
if (httpFileStream != null) httpFileStream.Dispose();
if (localFileStram != null) localFileStram.Dispose();
}
if (_threadCompleteNum == _threadNum)
{
Complete();
_isComplete = true;
}
}
/// <summary>
/// 下載完成后合并文件塊
/// </summary>
private void Complete()
{
Stream mergeFile = null;
BinaryWriter AddWriter = null;
try
{
using (mergeFile = new FileStream(@_savePath, FileMode.Create)) //根據(jù)實(shí)際情況調(diào)整FileMode
{
AddWriter = new BinaryWriter(mergeFile);
foreach (string file in _tempFiles)
{
using (FileStream fs = new FileStream(file, FileMode.Open))
{
BinaryReader TempReader = new BinaryReader(fs);
AddWriter.Write(TempReader.ReadBytes((int)fs.Length));
TempReader.Close();
}
File.Delete(file);
}
}
MyMessageBox.Show("下載完成!");
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
if (AddWriter != null)
{
AddWriter.Close();
AddWriter.Dispose();
}
if (mergeFile != null)
{
mergeFile.Close();
mergeFile.Dispose();
}
}
}
}
總結(jié)
以上所述是小編給大家介紹的C# 文件上傳下載(Excel導(dǎo)入,多線程下載)功能的實(shí)現(xiàn)代碼,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)我們網(wǎng)站的支持!
上一篇:C#實(shí)現(xiàn)簡(jiǎn)單的loading提示控件實(shí)例代碼
欄 目:C#教程
下一篇:C#設(shè)計(jì)模式之Observer觀察者模式解決牛頓童鞋成績(jī)問(wèn)題示例
本文標(biāo)題:C# 文件上傳下載(Excel導(dǎo)入,多線程下載)功能的實(shí)現(xiàn)代碼
本文地址:http://www.jygsgssxh.com/a1/C_jiaocheng/5514.html
您可能感興趣的文章
- 01-10C#實(shí)現(xiàn)多線程下載文件的方法
- 01-10C#文件斷點(diǎn)續(xù)傳實(shí)現(xiàn)方法
- 01-10C#實(shí)現(xiàn)多線程寫入同一個(gè)文件的方法
- 01-10C#編程獲取資源文件中圖片的方法
- 01-10C#實(shí)現(xiàn)讀取被進(jìn)程占用的文件實(shí)現(xiàn)方法
- 01-10C#刪除只讀文件或文件夾(解決File.Delete無(wú)法刪除文件)
- 01-10C# readnodefile()不能讀取帶有文件名為漢字的osg文件解決方法
- 01-10C#路徑,文件,目錄及IO常見(jiàn)操作匯總
- 01-10winform實(shí)現(xiàn)拖動(dòng)文件到窗體上的方法
- 01-10C#讀寫INI文件的方法


閱讀排行
- 1C語(yǔ)言 while語(yǔ)句的用法詳解
- 2java 實(shí)現(xiàn)簡(jiǎn)單圣誕樹(shù)的示例代碼(圣誕
- 3利用C語(yǔ)言實(shí)現(xiàn)“百馬百擔(dān)”問(wèn)題方法
- 4C語(yǔ)言中計(jì)算正弦的相關(guān)函數(shù)總結(jié)
- 5c語(yǔ)言計(jì)算三角形面積代碼
- 6什么是 WSH(腳本宿主)的詳細(xì)解釋
- 7C++ 中隨機(jī)函數(shù)random函數(shù)的使用方法
- 8正則表達(dá)式匹配各種特殊字符
- 9C語(yǔ)言十進(jìn)制轉(zhuǎn)二進(jìn)制代碼實(shí)例
- 10C語(yǔ)言查找數(shù)組里數(shù)字重復(fù)次數(shù)的方法
本欄相關(guān)
- 01-10C#通過(guò)反射獲取當(dāng)前工程中所有窗體并
- 01-10關(guān)于ASP網(wǎng)頁(yè)無(wú)法打開(kāi)的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實(shí)現(xiàn)txt定位指定行完整實(shí)例
- 01-10WinForm實(shí)現(xiàn)仿視頻播放器左下角滾動(dòng)新
- 01-10C#停止線程的方法
- 01-10C#實(shí)現(xiàn)清空回收站的方法
- 01-10C#通過(guò)重寫Panel改變邊框顏色與寬度的
- 01-10C#實(shí)現(xiàn)讀取注冊(cè)表監(jiān)控當(dāng)前操作系統(tǒng)已
隨機(jī)閱讀
- 08-05DEDE織夢(mèng)data目錄下的sessions文件夾有什
- 01-11Mac OSX 打開(kāi)原生自帶讀寫NTFS功能(圖文
- 01-11ajax實(shí)現(xiàn)頁(yè)面的局部加載
- 01-10delphi制作wav文件的方法
- 08-05織夢(mèng)dedecms什么時(shí)候用欄目交叉功能?
- 01-10SublimeText編譯C開(kāi)發(fā)環(huán)境設(shè)置
- 08-05dedecms(織夢(mèng))副欄目數(shù)量限制代碼修改
- 01-10C#中split用法實(shí)例總結(jié)
- 04-02jquery與jsp,用jquery
- 01-10使用C語(yǔ)言求解撲克牌的順子及n個(gè)骰子


