项目里最近需要在生成的报表中插入条形码,而条形码需要程序自己生成,在网上经过搜索及自己尝试自己之后,终于将问题解决,要解决这个问题,我是分两步来将它完成的。
第一步:生成对应的条形码,并把它们放在指定的文件夹中
第二步:在系统预生成的excel文件的某个指定的单元格中
第三步:将之前已生成好的条形码插入其中
现在,我先解决前两个问题,要解决这个问题,在网上有很多的方法,我这里只记录自己尝试过,并成功的内容。
首先,需要下载这个条形码生成需要的相关dll引用,我在这里先放上这个dll链接,链接:https://pan.baidu.com/s/15g_O8OgAC9iUBzHVhfRUYw
提取码:b969
这里先放上生成条形码的函数。
//根据string生成条形码 jin-begin
public static void GetBarcode(int height, int width, BarcodeLib.TYPE type, string code, out System.Drawing.Image image, string fileSaveUrl)
{
try
{
image = null;
BarcodeLib.Barcode b = new BarcodeLib.Barcode();
b.BackColor = System.Drawing.Color.White;//图片背景颜色
b.ForeColor = System.Drawing.Color.Black;//条码颜色
b.IncludeLabel = true;
b.Alignment = BarcodeLib.AlignmentPositions.LEFT;
b.LabelPosition = BarcodeLib.LabelPositions.BOTTOMCENTER;//code的显示位置
b.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;//图片格式
System.Drawing.Font font = new System.Drawing.Font("verdana", 10f);//字体设置
b.LabelFont = font;
b.Height = height;//图片高度设置(px单位)
b.Width = width;//图片宽度设置(px单位)
image = b.Encode(type, code);//生成图片
image.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (Exception ex)
{
image = null;
}
}
而在主要调用的地方我是这么调用的,由于我想要把生成的条形码放在当前项目路径下的某个文件夹,而这个文件夹如果不存在,则需要新建。
新建文件夹的程序如下所示:
//在当前路径下创建文件夹,用于存放条形码 jin
//获取当前文件夹路径
string currPath = Application.StartupPath;
//检查是否存在文件夹
string subPath = currPath + "\\pic\\";
if (false == System.IO.Directory.Exists(subPath))
{
//创建pic文件夹
System.IO.Directory.CreateDirectory(subPath);
}
生成条形码并保存在这个路径下的程序如下所示,其中的col3是我读取到的字符串,可以是非数字
//生成条形码并保存到本地,文件格式,jpg
string fileSavePath = "";
if (!col3.Equals(""))
{
System.Drawing.Image image;
int width = 148, height = 55;
string str = col3.Split('*')[1];
fileSavePath = subPath + str + ".jpg";
if (File.Exists(fileSavePath))
File.Delete(fileSavePath);
GetBarcode(height, width, BarcodeLib.TYPE.CODE128, col3, out image, fileSavePath);
}
第三个问题的解决见:https://blog.csdn.net/qq_40467670/article/details/120281772