Introduction
I have already introduced you to a barcode generating a library in my blog (
A Barcode Generating Library). This article provides more practice with the library. This practice is closer to real life. And I hope it will be more useful.
Let's think about this scenario
We get many barcodes to deal with. And the types of barcode is stored in one column of an Excel file. The data of the barcode is stored in another column of Excel file as shown in the picture above. We need to generate barcode images using the data in the Excel file. Barcode images will then be used to identify goods in the logistics business or supermarket. Remember that there are many of them. It is quite unwise to generate them manually.
We need a better solution to get the data from the Excel file. And with the help of this library (you can download it here:
https://freenetexcel.codeplex.com/), we can fulfill the job easily. Please check the code in the next part.
Sample Code
In this part, I will introduce you to the sample code in the attachment.
Step 1: Load the Excel file.
- Workbook workbook = new Workbook();
- workbook.LoadFromFile("SourceFile.xlsx");
- Worksheet sheet = workbook.Worksheets[0];
Step 2: Get the data from the Excel file using a for loop.
- int i;
- string barcodeType,barcodeData;
- for (i = 2; i<=sheet.AllocatedRange.Rows.Count(); i++)
- {
- barcodeType = sheet.Range[i, 1].Text;
- barcodeData = sheet.Range[i, 2].Text;
- }
Step 3: Generate barcode images.
- BarcodeSettings barsetting = new BarcodeSettings();
- barsetting.HasBorder = true;
- barsetting.BorderWidth = 0.5F;
- barsetting.ShowTextOnBottom = true;
- barsetting.Data = barcodeData;
- barsetting.Data2D = barcodeData;
- barsetting.Type = (BarCodeType)Enum.Parse(typeof(BarCodeType), barcodeType);
-
- BarCodeGenerator bargenerator = new BarCodeGenerator(barsetting);
- Image barcodeimage = bargenerator.GenerateImage();
- String fileName = String.Format("Image-{0}.png", i);
- barcodeimage.Save(fileName);
Step 4: Add the barcode images to the Excel file.
- sheet.Pictures.Add(i, 3, fileName);
Outcome
This is the screenshot of the final Excel file.