C#已知图片路径或图片字节流,此法实现把已知图片路径或图片字节流插入到指定的exce文件
/// <summary>
/// 根据图片路径url把图片插入到相应的exce文件中
/// </summary>
/// <param name="url">图片路径</param>
/// <param name="sheet">要导入的excel的sheet的名称</param>
/// <param name="column">要导入的excel的所在列数</param>
/// <param name="row">要导入的excel的所在行数</param>
public static void CreateRowForImg(string url, string sheetName, int column, int row)
{
//插入图片
try
{
IWorkbook workbook = null;
ISheet sheet = workbook.CreateSheet(sheetName);
var workType = 2007;
try
{
workbook = new XSSFWorkbook();// 2007版本
}
catch (Exception)
{
workType = 2003;
workbook = new HSSFWorkbook();// 2003版本
}
if (workbook == null)
{
return;
}
//获取图片字节流
byte[] bytes = GetPictureData(url);//获取图片信息
if (bytes.Length > 0)
{
int pictureIdx = workbook.AddPicture(bytes, NPOI.SS.UserModel.PictureType.JPEG);
var patriarch = sheet.CreateDrawingPatriarch();
if (workType == 2007)// 2007版本
{
XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 200, 100, column + 1, row + 1, column + 2, row + 2);
//##处理照片位置,【图片左上角为(col, row)第row+1行col+1列,右下角为( col +1, row +1)第 col +1+1行row +1+1列,宽为100,高为50
XSSFPicture pict = (XSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
}
else
{
// 2003版本
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 100, 50, column + 1, row + 1, column + 2, row + 2);
//##处理照片位置,【图片左上角为(col, row)第row+1行col+1列,右下角为( col +1, row +1)第 col +1+1行row +1+1列,宽为100,高为50
HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
}
}
}
catch (Exception ex)
{
throw ex;
}
}
//参数是图片的路径
public static byte[] GetPictureData(string url)
{
try
{
var wreq = HttpWebRequest.Create(url) as HttpWebRequest;
HttpWebResponse response = wreq.GetResponse() as HttpWebResponse;
Byte[] byteData = new Byte[response.ContentLength];
using (var stream = response.GetResponseStream())
{
int offset = 0, actuallyRead = 0;
do
{
actuallyRead = stream.Read(byteData, offset, byteData.Length - offset);
offset += actuallyRead;
}
while (actuallyRead > 0);
}
response.Close();
return byteData;
}
catch { }
return new Byte[0];
}