本文章主要解决
1.C#环境下按行读取Excel内容
2.从FTP服务器上下载图片
按行读取Excel内容
/// <summary>
/// 读取Excel内容
/// </summary>
/// <param name="vFilePath">Excel位置</param>
/// <param name="worksheetIndex">工作表索引</param>
/// <exception cref="Exception"></exception>
public void ReadXlsx(string vFilePath, int worksheetIndex)
{
try
{
using (ExcelPackage package = new ExcelPackage(new FileInfo(vFilePath)))
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
ExcelWorksheet worksheet = package.Workbook.Worksheets[worksheetIndex];
for (int rowNumber = 2; rowNumber <= worksheet.Dimension.End.Row; rowNumber++)
{
var row = worksheet.Cells[rowNumber, 1, rowNumber, worksheet.Dimension.End.Column];
string type="";
string imagepath="";
foreach (var cell in row)
{
if (cell.Start.Column == 1)
{
type = cell.Text;
}
else
{
imagepath=cell.Text;
}
}
DownImage(type, imagepath);
}
}
}
catch (Exception ex)
{
throw new Exception("Xlsx to DataTable: \n" + ex.Message);
}
}
从服务器中下载图片
/// <summary>
/// 下载图片并保存
/// </summary>
/// <param name="type">图片类型</param>
/// <param name="path">图片在FTP中保存的位置</param>
public void DownImage(string type,string path)
{
string folderPath = curfolderpath + "\\" + type;
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(folderPath);
var index=dirInfo.GetFiles().Count();
string ftpserver = ftpServer;
string filePath = path;
string username = ftpUserID;
string password = ftpPassword;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpserver + filePath);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(username, password);
using(var response=(FtpWebResponse)request.GetResponse())
{
using(Stream stream = response.GetResponseStream())
{
var BUF_SIZE = (int)response.ContentLength;
string filename = folderPath + "\\" + index.ToString() + ".jpg";
using (FileStream fileStream=new FileStream(filename, FileMode.Create))
{
byte[] buffer = new byte[BUF_SIZE];
int bytesRead = 0;
while ((bytesRead = stream.Read(buffer,0,buffer.Length)) > 0)
{
fileStream.Write(buffer,0,bytesRead);
}
}
index++;
}
}
}
定义的全局变量
string ftpServer; //ftp服务器地址
string ftpUserID; //ftp服务器用户名
string ftpPassword; //ftp服务器密码
string curfolderpath; //保存文件的文件夹路径