快递单打印解决方案,支持多种快递公司模板、自定义打印位置、批量打印、数据导入等功能。
一、项目结构
ExpressPrintSystem/
├── MainForm.cs # 主窗体
├── TemplateEditorForm.cs # 模板编辑器
├── PrintPreviewForm.cs # 打印预览
├── DataImportForm.cs # 数据导入
├── ExpressTemplate.cs # 快递模板管理
├── PrintEngine.cs # 打印引擎
├── DataSource.cs # 数据源管理
├── ConfigManager.cs # 配置管理
└── ExpressPrintSystem.csproj
二、核心源码实现
2.1 项目文件 (ExpressPrintSystem.csproj)
xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ClosedXML" Version="0.102.2" />
<PackageReference Include="DocumentFormat.OpenXml" Version="2.20.0" />
<PackageReference Include="System.Drawing.Common" Version="7.0.0" />
</ItemGroup>
</Project>
2.2 快递模板类 (ExpressTemplate.cs)
csharp
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Xml.Serialization;
namespace ExpressPrintSystem
{
/// <summary>
/// 快递模板类
/// </summary>
[XmlRoot("ExpressTemplate")]
public class ExpressTemplate
{
[XmlElement("TemplateName")]
public string TemplateName { get; set; } = "";
[XmlElement("CompanyName")]
public string CompanyName { get; set; } = "";
[XmlElement("PageSize")]
public PageSize PageSize { get; set; } = new PageSize();
[XmlElement("Margin")]
public Margin Margin { get; set; } = new Margin();
[XmlArray("PrintItems")]
[XmlArrayItem("PrintItem")]
public List<PrintItem> PrintItems { get; set; } = new List<PrintItem>();
[XmlElement("IsDefault")]
public bool IsDefault { get; set; } = false;
[XmlElement("CreatedDate")]
public DateTime CreatedDate { get; set; } = DateTime.Now;
[XmlElement("ModifiedDate")]
public DateTime ModifiedDate { get; set; } = DateTime.Now;
}
/// <summary>
/// 页面尺寸
/// </summary>
public class PageSize
{
[XmlElement("Width")]
public float Width { get; set; } = 210f; // A4宽度(mm)
[XmlElement("Height")]
public float Height { get; set; } = 297f; // A4高度(mm)
[XmlElement("Unit")]
public string Unit { get; set; } = "mm";
}
/// <summary>
/// 页边距
/// </summary>
public class Margin
{
[XmlElement("Left")]
public float Left { get; set; } = 10f;
[XmlElement("Top")]
public float Top { get; set; } = 10f;
[XmlElement("Right")]
public float Right { get; set; } = 10f;
[XmlElement("Bottom")]
public float Bottom { get; set; } = 10f;
}
/// <summary>
/// 打印项
/// </summary>
public class PrintItem
{
[XmlElement("Name")]
public string Name { get; set; } = "";
[XmlElement("Type")]
public PrintItemType Type { get; set; } = PrintItemType.Text;
[XmlElement("X")]
public float X { get; set; } = 0f; // X坐标(mm)
[XmlElement("Y")]
public float Y { get; set; } = 0f; // Y坐标(mm)
[XmlElement("Width")]
public float Width { get; set; } = 50f;
[XmlElement("Height")]
public float Height { get; set; } = 10f;
[XmlElement("Content")]
public string Content { get; set; } = "";
[XmlElement("FontFamily")]
public string FontFamily { get; set; } = "宋体";
[XmlElement("FontSize")]
public float FontSize { get; set; } = 10f;
[XmlElement("FontStyle")]
public FontStyle FontStyle { get; set; } = FontStyle.Regular;
[XmlElement("Alignment")]
public StringAlignment Alignment { get; set; } = StringAlignment.Near;
[XmlElement("ForeColor")]
public string ForeColor { get; set; } = "#000000";
[XmlElement("BackColor")]
public string BackColor { get; set; } = "#FFFFFF";
[XmlElement("BorderWidth")]
public float BorderWidth { get; set; } = 0f;
[XmlElement("BorderColor")]
public string BorderColor { get; set; } = "#000000";
[XmlElement("Rotation")]
public float Rotation { get; set; } = 0f;
[XmlElement("Visible")]
public bool Visible { get; set; } = true;
[XmlElement("DataSourceField")]
public string DataSourceField { get; set; } = "";
}
/// <summary>
/// 打印项类型
/// </summary>
public enum PrintItemType
{
Text,
Barcode,
QRCode,
Image,
Line,
Rectangle
}
/// <summary>
/// 字体样式
/// </summary>
[Flags]
public enum FontStyle
{
Regular = 0,
Bold = 1,
Italic = 2,
Underline = 4,
Strikeout = 8
}
/// <summary>
/// 字符串对齐方式
/// </summary>
public enum StringAlignment
{
Near = 0,
Center = 1,
Far = 2
}
}
2.3 打印引擎 (PrintEngine.cs)
csharp
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.Xml.Serialization;
namespace ExpressPrintSystem
{
/// <summary>
/// 打印引擎
/// </summary>
public class PrintEngine
{
private ExpressTemplate template;
private Dictionary<string, object> data;
private PrintDocument printDocument;
private int currentPageIndex = 0;
public PrintEngine(ExpressTemplate template)
{
this.template = template;
this.printDocument = new PrintDocument();
this.printDocument.PrintPage += PrintDocument_PrintPage;
}
/// <summary>
/// 打印单个订单
/// </summary>
public void PrintOrder(Dictionary<string, object> orderData)
{
this.data = orderData;
this.currentPageIndex = 0;
printDocument.Print();
}
/// <summary>
/// 批量打印
/// </summary>
public void PrintBatch(List<Dictionary<string, object>> orders)
{
foreach (var order in orders)
{
PrintOrder(order);
}
}
/// <summary>
/// 打印预览
/// </summary>
public void PrintPreview(Dictionary<string, object> orderData)
{
this.data = orderData;
this.currentPageIndex = 0;
PrintPreviewDialog previewDialog = new PrintPreviewDialog();
previewDialog.Document = printDocument;
previewDialog.ShowDialog();
}
/// <summary>
/// 打印页面事件
/// </summary>
private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
{
Graphics g = e.Graphics;
g.PageUnit = GraphicsUnit.Millimeter;
// 设置页面边距
g.TranslateTransform(template.Margin.Left, template.Margin.Top);
// 绘制所有打印项
foreach (var item in template.PrintItems)
{
if (!item.Visible) continue;
// 替换数据源字段
string content = ReplaceDataSourceFields(item.Content, data);
// 绘制打印项
DrawPrintItem(g, item, content);
}
e.HasMorePages = false;
}
/// <summary>
/// 绘制打印项
/// </summary>
private void DrawPrintItem(Graphics g, PrintItem item, string content)
{
// 设置字体
FontStyle fontStyle = item.FontStyle;
using Font font = new Font(item.FontFamily, item.FontSize, (System.Drawing.FontStyle)fontStyle);
// 设置画刷
using SolidBrush brush = new SolidBrush(ColorTranslator.FromHtml(item.ForeColor));
// 设置边框
using Pen pen = new Pen(ColorTranslator.FromHtml(item.BorderColor), item.BorderWidth);
// 创建矩形区域
RectangleF rect = new RectangleF(item.X, item.Y, item.Width, item.Height);
// 根据类型绘制
switch (item.Type)
{
case PrintItemType.Text:
DrawText(g, item, content, font, brush, rect);
break;
case PrintItemType.Barcode:
DrawBarcode(g, item, content, rect);
break;
case PrintItemType.QRCode:
DrawQRCode(g, item, content, rect);
break;
case PrintItemType.Image:
DrawImage(g, item, content, rect);
break;
case PrintItemType.Line:
DrawLine(g, item, pen, rect);
break;
case PrintItemType.Rectangle:
DrawRectangle(g, item, pen, brush, rect);
break;
}
}
/// <summary>
/// 绘制文本
/// </summary>
private void DrawText(Graphics g, PrintItem item, string content, Font font, Brush brush, RectangleF rect)
{
StringFormat sf = new StringFormat();
sf.Alignment = (StringAlignment)item.Alignment;
sf.LineAlignment = StringAlignment.Center;
g.DrawString(content, font, brush, rect, sf);
}
/// <summary>
/// 绘制条形码
/// </summary>
private void DrawBarcode(Graphics g, PrintItem item, string content, RectangleF rect)
{
try
{
// 使用ZXing生成条形码
var writer = new ZXing.BarcodeWriter
{
Format = ZXing.BarcodeFormat.CODE_128,
Options = new ZXing.Common.EncodingOptions
{
Width = (int)(rect.Width * 3.78f), // 转换为像素
Height = (int)(rect.Height * 3.78f),
Margin = 1
}
};
using Bitmap barcode = writer.Write(content);
g.DrawImage(barcode, rect);
}
catch
{
// 如果生成失败,绘制文本
using Font font = new Font("Arial", item.FontSize);
using SolidBrush brush = new SolidBrush(Color.Black);
g.DrawString(content, font, brush, rect);
}
}
/// <summary>
/// 绘制二维码
/// </summary>
private void DrawQRCode(Graphics g, PrintItem item, string content, RectangleF rect)
{
try
{
var writer = new ZXing.BarcodeWriter
{
Format = ZXing.BarcodeFormat.QR_CODE,
Options = new ZXing.Common.EncodingOptions
{
Width = (int)(rect.Width * 3.78f),
Height = (int)(rect.Height * 3.78f),
Margin = 1
}
};
using Bitmap qrcode = writer.Write(content);
g.DrawImage(qrcode, rect);
}
catch
{
using Font font = new Font("Arial", 8);
using SolidBrush brush = new SolidBrush(Color.Black);
g.DrawString("QR:" + content, font, brush, rect);
}
}
/// <summary>
/// 绘制图片
/// </summary>
private void DrawImage(Graphics g, PrintItem item, string content, RectangleF rect)
{
try
{
if (File.Exists(content))
{
using Bitmap image = new Bitmap(content);
g.DrawImage(image, rect);
}
}
catch
{
// 图片加载失败,绘制占位符
using Pen pen = new Pen(Color.Red, 1);
g.DrawRectangle(pen, rect.X, rect.Y, rect.Width, rect.Height);
g.DrawLine(pen, rect.X, rect.Y, rect.X + rect.Width, rect.Y + rect.Height);
g.DrawLine(pen, rect.X + rect.Width, rect.Y, rect.X, rect.Y + rect.Height);
}
}
/// <summary>
/// 绘制线条
/// </summary>
private void DrawLine(Graphics g, PrintItem item, Pen pen, RectangleF rect)
{
g.DrawLine(pen, rect.X, rect.Y, rect.X + rect.Width, rect.Y + rect.Height);
}
/// <summary>
/// 绘制矩形
/// </summary>
private void DrawRectangle(Graphics g, PrintItem item, Pen pen, Brush brush, RectangleF rect)
{
g.DrawRectangle(pen, rect.X, rect.Y, rect.Width, rect.Height);
if (item.BackColor != "#FFFFFF")
{
g.FillRectangle(brush, rect);
}
}
/// <summary>
/// 替换数据源字段
/// </summary>
private string ReplaceDataSourceFields(string content, Dictionary<string, object> data)
{
if (string.IsNullOrEmpty(content) || data == null) return content;
string result = content;
foreach (var kvp in data)
{
result = result.Replace($"{{{kvp.Key}}}", kvp.Value?.ToString() ?? "");
}
return result;
}
}
}
2.4 模板管理器 (ExpressTemplateManager.cs)
csharp
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
namespace ExpressPrintSystem
{
/// <summary>
/// 快递模板管理器
/// </summary>
public static class ExpressTemplateManager
{
private static readonly string TemplateFolder = "Templates";
private static List<ExpressTemplate> templates = new List<ExpressTemplate>();
static ExpressTemplateManager()
{
LoadAllTemplates();
}
/// <summary>
/// 加载所有模板
/// </summary>
public static void LoadAllTemplates()
{
if (!Directory.Exists(TemplateFolder))
{
Directory.CreateDirectory(TemplateFolder);
CreateDefaultTemplates();
}
templates.Clear();
string[] files = Directory.GetFiles(TemplateFolder, "*.xml");
foreach (string file in files)
{
try
{
ExpressTemplate template = LoadTemplate(file);
if (template != null)
{
templates.Add(template);
}
}
catch (Exception ex)
{
Console.WriteLine($"加载模板失败: {ex.Message}");
}
}
}
/// <summary>
/// 加载单个模板
/// </summary>
public static ExpressTemplate LoadTemplate(string filePath)
{
XmlSerializer serializer = new XmlSerializer(typeof(ExpressTemplate));
using FileStream fs = new FileStream(filePath, FileMode.Open);
return (ExpressTemplate)serializer.Deserialize(fs);
}
/// <summary>
/// 保存模板
/// </summary>
public static void SaveTemplate(ExpressTemplate template)
{
string fileName = Path.Combine(TemplateFolder, $"{template.TemplateName}.xml");
XmlSerializer serializer = new XmlSerializer(typeof(ExpressTemplate));
using FileStream fs = new FileStream(fileName, FileMode.Create);
serializer.Serialize(fs, template);
}
/// <summary>
/// 创建默认模板
/// </summary>
private static void CreateDefaultTemplates()
{
// 顺丰模板
ExpressTemplate sfTemplate = new ExpressTemplate
{
TemplateName = "顺丰速运",
CompanyName = "顺丰速运",
PageSize = new PageSize { Width = 100, Height = 150 },
Margin = new Margin { Left = 5, Top = 5, Right = 5, Bottom = 5 }
};
sfTemplate.PrintItems.Add(new PrintItem
{
Name = "收件人姓名",
Type = PrintItemType.Text,
X = 10, Y = 20, Width = 80, Height = 10,
Content = "{ReceiverName}",
FontSize = 12, FontStyle = FontStyle.Bold
});
sfTemplate.PrintItems.Add(new PrintItem
{
Name = "收件人电话",
Type = PrintItemType.Text,
X = 10, Y = 35, Width = 80, Height = 10,
Content = "{ReceiverPhone}",
FontSize = 10
});
sfTemplate.PrintItems.Add(new PrintItem
{
Name = "收件地址",
Type = PrintItemType.Text,
X = 10, Y = 50, Width = 80, Height = 20,
Content = "{ReceiverAddress}",
FontSize = 9
});
sfTemplate.PrintItems.Add(new PrintItem
{
Name = "快递单号",
Type = PrintItemType.Barcode,
X = 10, Y = 80, Width = 80, Height = 15,
Content = "{WaybillNo}"
});
SaveTemplate(sfTemplate);
// 圆通模板
ExpressTemplate ytTemplate = new ExpressTemplate
{
TemplateName = "圆通速递",
CompanyName = "圆通速递",
PageSize = new PageSize { Width = 100, Height = 180 }
};
ytTemplate.PrintItems.Add(new PrintItem
{
Name = "寄件人信息",
Type = PrintItemType.Text,
X = 5, Y = 10, Width = 90, Height = 30,
Content = "寄件人: {SenderName}\n电话: {SenderPhone}\n地址: {SenderAddress}",
FontSize = 9
});
ytTemplate.PrintItems.Add(new PrintItem
{
Name = "收件人信息",
Type = PrintItemType.Text,
X = 5, Y = 50, Width = 90, Height = 40,
Content = "收件人: {ReceiverName}\n电话: {ReceiverPhone}\n地址: {ReceiverAddress}",
FontSize = 10
});
ytTemplate.PrintItems.Add(new PrintItem
{
Name = "运单号",
Type = PrintItemType.Barcode,
X = 5, Y = 100, Width = 90, Height = 20,
Content = "{WaybillNo}"
});
SaveTemplate(ytTemplate);
}
/// <summary>
/// 获取所有模板
/// </summary>
public static List<ExpressTemplate> GetAllTemplates()
{
return templates;
}
/// <summary>
/// 获取默认模板
/// </summary>
public static ExpressTemplate GetDefaultTemplate()
{
return templates.Find(t => t.IsDefault) ?? templates[0];
}
/// <summary>
/// 删除模板
/// </summary>
public static void DeleteTemplate(string templateName)
{
string fileName = Path.Combine(TemplateFolder, $"{templateName}.xml");
if (File.Exists(fileName))
{
File.Delete(fileName);
LoadAllTemplates();
}
}
}
}
2.5 主窗体 (MainForm.cs)
csharp
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace ExpressPrintSystem
{
public partial class MainForm : Form
{
private PrintEngine printEngine;
private List<Dictionary<string, object>> orderDataList = new List<Dictionary<string, object>>();
public MainForm()
{
InitializeComponent();
LoadTemplates();
CreateSampleData();
}
private void LoadTemplates()
{
cmbTemplates.Items.Clear();
var templates = ExpressTemplateManager.GetAllTemplates();
foreach (var template in templates)
{
cmbTemplates.Items.Add(template.TemplateName);
}
if (cmbTemplates.Items.Count > 0)
{
cmbTemplates.SelectedIndex = 0;
}
}
private void CreateSampleData()
{
// 创建示例订单数据
Dictionary<string, object> order1 = new Dictionary<string, object>
{
["ReceiverName"] = "张三",
["ReceiverPhone"] = "13800138000",
["ReceiverAddress"] = "北京市朝阳区建国路100号",
["SenderName"] = "李四",
["SenderPhone"] = "13900139000",
["SenderAddress"] = "上海市浦东新区张江高科技园区",
["WaybillNo"] = "SF1234567890",
["GoodsName"] = "电子产品",
["Weight"] = "2.5kg",
["Remark"] = "易碎品,轻拿轻放"
};
Dictionary<string, object> order2 = new Dictionary<string, object>
{
["ReceiverName"] = "王五",
["ReceiverPhone"] = "13700137000",
["ReceiverAddress"] = "广州市天河区体育西路200号",
["SenderName"] = "赵六",
["SenderPhone"] = "13600136000",
["SenderAddress"] = "深圳市南山区科技园",
["WaybillNo"] = "YT9876543210",
["GoodsName"] = "服装",
["Weight"] = "1.2kg",
["Remark"] = "急件"
};
orderDataList.Add(order1);
orderDataList.Add(order2);
// 更新订单列表
lstOrders.Items.Clear();
for (int i = 0; i < orderDataList.Count; i++)
{
lstOrders.Items.Add($"订单 {i + 1}: {orderDataList[i]["ReceiverName"]} - {orderDataList[i]["WaybillNo"]}");
}
}
private void btnPrintPreview_Click(object sender, EventArgs e)
{
if (lstOrders.SelectedIndex < 0)
{
MessageBox.Show("请选择要打印的订单!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
string templateName = cmbTemplates.SelectedItem.ToString();
var template = ExpressTemplateManager.GetAllTemplates().Find(t => t.TemplateName == templateName);
if (template == null)
{
MessageBox.Show("模板不存在!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
printEngine = new PrintEngine(template);
printEngine.PrintPreview(orderDataList[lstOrders.SelectedIndex]);
}
private void btnPrint_Click(object sender, EventArgs e)
{
if (lstOrders.SelectedIndex < 0)
{
MessageBox.Show("请选择要打印的订单!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
string templateName = cmbTemplates.SelectedItem.ToString();
var template = ExpressTemplateManager.GetAllTemplates().Find(t => t.TemplateName == templateName);
if (template == null)
{
MessageBox.Show("模板不存在!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
printEngine = new PrintEngine(template);
printEngine.PrintOrder(orderDataList[lstOrders.SelectedIndex]);
MessageBox.Show("打印任务已发送到打印机!", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void btnBatchPrint_Click(object sender, EventArgs e)
{
if (lstOrders.Items.Count == 0)
{
MessageBox.Show("没有可打印的订单!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
string templateName = cmbTemplates.SelectedItem.ToString();
var template = ExpressTemplateManager.GetAllTemplates().Find(t => t.TemplateName == templateName);
if (template == null)
{
MessageBox.Show("模板不存在!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
printEngine = new PrintEngine(template);
printEngine.PrintBatch(orderDataList);
MessageBox.Show($"批量打印完成!共打印 {orderDataList.Count} 个订单。", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void btnTemplateEditor_Click(object sender, EventArgs e)
{
TemplateEditorForm editorForm = new TemplateEditorForm();
editorForm.ShowDialog();
LoadTemplates(); // 刷新模板列表
}
private void btnDataImport_Click(object sender, EventArgs e)
{
DataImportForm importForm = new DataImportForm();
if (importForm.ShowDialog() == DialogResult.OK)
{
// 刷新订单列表
lstOrders.Items.Clear();
for (int i = 0; i < orderDataList.Count; i++)
{
lstOrders.Items.Add($"订单 {i + 1}: {orderDataList[i]["ReceiverName"]} - {orderDataList[i]["WaybillNo"]}");
}
}
}
#region Windows Form Designer generated code
private System.ComponentModel.IContainer components = null;
private MenuStrip menuStrip1;
private ToolStripMenuItem 文件ToolStripMenuItem;
private ToolStripMenuItem 退出ToolStripMenuItem;
private ToolStripMenuItem 模板管理ToolStripMenuItem;
private ToolStripMenuItem 模板编辑器ToolStripMenuItem;
private ToolStripMenuItem 数据导入ToolStripMenuItem;
private GroupBox groupBox1;
private ComboBox cmbTemplates;
private Label label1;
private GroupBox groupBox2;
private ListBox lstOrders;
private Button btnPrintPreview;
private Button btnPrint;
private Button btnBatchPrint;
private Button btnTemplateEditor;
private Button btnDataImport;
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.文件ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.退出ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.模板管理ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.模板编辑器ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.数据导入ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.cmbTemplates = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.lstOrders = new System.Windows.Forms.ListBox();
this.btnPrintPreview = new System.Windows.Forms.Button();
this.btnPrint = new System.Windows.Forms.Button();
this.btnBatchPrint = new System.Windows.Forms.Button();
this.btnTemplateEditor = new System.Windows.Forms.Button();
this.btnDataImport = new System.Windows.Forms.Button();
this.menuStrip1.SuspendLayout();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.SuspendLayout();
// menuStrip1
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.文件ToolStripMenuItem,
this.模板管理ToolStripMenuItem,
this.数据导入ToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(800, 25);
this.menuStrip1.TabIndex = 0;
this.menuStrip1.Text = "menuStrip1";
// 文件ToolStripMenuItem
this.文件ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.退出ToolStripMenuItem});
this.文件ToolStripMenuItem.Name = "文件ToolStripMenuItem";
this.文件ToolStripMenuItem.Size = new System.Drawing.Size(44, 21);
this.文件ToolStripMenuItem.Text = "文件";
// 退出ToolStripMenuItem
this.退出ToolStripMenuItem.Name = "退出ToolStripMenuItem";
this.退出ToolStripMenuItem.Size = new System.Drawing.Size(93, 22);
this.退出ToolStripMenuItem.Text = "退出";
this.退出ToolStripMenuItem.Click += new System.EventHandler(this.退出ToolStripMenuItem_Click);
// 模板管理ToolStripMenuItem
this.模板管理ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.模板编辑器ToolStripMenuItem});
this.模板管理ToolStripMenuItem.Name = "模板管理ToolStripMenuItem";
this.模板管理ToolStripMenuItem.Size = new System.Drawing.Size(68, 21);
this.模板管理ToolStripMenuItem.Text = "模板管理";
// 模板编辑器ToolStripMenuItem
this.模板编辑器ToolStripMenuItem.Name = "模板编辑器ToolStripMenuItem";
this.模板编辑器ToolStripMenuItem.Size = new System.Drawing.Size(124, 22);
this.模板编辑器ToolStripMenuItem.Text = "模板编辑器";
this.模板编辑器ToolStripMenuItem.Click += new System.EventHandler(this.btnTemplateEditor_Click);
// 数据导入ToolStripMenuItem
this.数据导入ToolStripMenuItem.Name = "数据导入ToolStripMenuItem";
this.数据导入ToolStripMenuItem.Size = new System.Drawing.Size(68, 21);
this.数据导入ToolStripMenuItem.Text = "数据导入";
this.数据导入ToolStripMenuItem.Click += new System.EventHandler(this.btnDataImport_Click);
// groupBox1
this.groupBox1.Controls.Add(this.cmbTemplates);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Location = new System.Drawing.Point(12, 30);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(300, 80);
this.groupBox1.TabIndex = 1;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "选择模板";
// cmbTemplates
this.cmbTemplates.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbTemplates.FormattingEnabled = true;
this.cmbTemplates.Location = new System.Drawing.Point(80, 30);
this.cmbTemplates.Name = "cmbTemplates";
this.cmbTemplates.Size = new System.Drawing.Size(200, 23);
this.cmbTemplates.TabIndex = 1;
// label1
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(20, 33);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(56, 13);
this.label1.TabIndex = 0;
this.label1.Text = "快递模板:";
// groupBox2
this.groupBox2.Controls.Add(this.lstOrders);
this.groupBox2.Location = new System.Drawing.Point(12, 120);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(300, 300);
this.groupBox2.TabIndex = 2;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "订单列表";
// lstOrders
this.lstOrders.FormattingEnabled = true;
this.lstOrders.Location = new System.Drawing.Point(20, 25);
this.lstOrders.Name = "lstOrders";
this.lstOrders.Size = new System.Drawing.Size(260, 260);
this.lstOrders.TabIndex = 0;
// btnPrintPreview
this.btnPrintPreview.Location = new System.Drawing.Point(330, 30);
this.btnPrintPreview.Name = "btnPrintPreview";
this.btnPrintPreview.Size = new System.Drawing.Size(100, 30);
this.btnPrintPreview.TabIndex = 3;
this.btnPrintPreview.Text = "打印预览";
this.btnPrintPreview.UseVisualStyleBackColor = true;
this.btnPrintPreview.Click += new System.EventHandler(this.btnPrintPreview_Click);
// btnPrint
this.btnPrint.Location = new System.Drawing.Point(330, 70);
this.btnPrint.Name = "btnPrint";
this.btnPrint.Size = new System.Drawing.Size(100, 30);
this.btnPrint.TabIndex = 4;
this.btnPrint.Text = "打印";
this.btnPrint.UseVisualStyleBackColor = true;
this.btnPrint.Click += new System.EventHandler(this.btnPrint_Click);
// btnBatchPrint
this.btnBatchPrint.Location = new System.Drawing.Point(330, 110);
this.btnBatchPrint.Name = "btnBatchPrint";
this.btnBatchPrint.Size = new System.Drawing.Size(100, 30);
this.btnBatchPrint.TabIndex = 5;
this.btnBatchPrint.Text = "批量打印";
this.btnBatchPrint.UseVisualStyleBackColor = true;
this.btnBatchPrint.Click += new System.EventHandler(this.btnBatchPrint_Click);
// btnTemplateEditor
this.btnTemplateEditor.Location = new System.Drawing.Point(450, 30);
this.btnTemplateEditor.Name = "btnTemplateEditor";
this.btnTemplateEditor.Size = new System.Drawing.Size(100, 30);
this.btnTemplateEditor.TabIndex = 6;
this.btnTemplateEditor.Text = "模板编辑器";
this.btnTemplateEditor.UseVisualStyleBackColor = true;
this.btnTemplateEditor.Click += new System.EventHandler(this.btnTemplateEditor_Click);
// btnDataImport
this.btnDataImport.Location = new System.Drawing.Point(450, 70);
this.btnDataImport.Name = "btnDataImport";
this.btnDataImport.Size = new System.Drawing.Size(100, 30);
this.btnDataImport.TabIndex = 7;
this.btnDataImport.Text = "数据导入";
this.btnDataImport.UseVisualStyleBackColor = true;
this.btnDataImport.Click += new System.EventHandler(this.btnDataImport_Click);
// MainForm
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.btnDataImport);
this.Controls.Add(this.btnTemplateEditor);
this.Controls.Add(this.btnBatchPrint);
this.Controls.Add(this.btnPrint);
this.Controls.Add(this.btnPrintPreview);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "MainForm";
this.Text = "快递单打印系统 - 万能套打系统";
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
#endregion
}
}
2.6 模板编辑器 (TemplateEditorForm.cs)
csharp
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace ExpressPrintSystem
{
public partial class TemplateEditorForm : Form
{
private ExpressTemplate currentTemplate;
private PrintItem selectedItem;
private bool isDragging = false;
private Point dragStartPoint;
public TemplateEditorForm()
{
InitializeComponent();
currentTemplate = new ExpressTemplate();
currentTemplate.TemplateName = "新模板";
UpdateTemplateInfo();
}
private void UpdateTemplateInfo()
{
txtTemplateName.Text = currentTemplate.TemplateName;
txtCompanyName.Text = currentTemplate.CompanyName;
numPageWidth.Value = (decimal)currentTemplate.PageSize.Width;
numPageHeight.Value = (decimal)currentTemplate.PageSize.Height;
numMarginLeft.Value = (decimal)currentTemplate.Margin.Left;
numMarginTop.Value = (decimal)currentTemplate.Margin.Top;
numMarginRight.Value = (decimal)currentTemplate.Margin.Right;
numMarginBottom.Value = (decimal)currentTemplate.Margin.Bottom;
// 更新打印项列表
lstPrintItems.Items.Clear();
foreach (var item in currentTemplate.PrintItems)
{
lstPrintItems.Items.Add($"{item.Name} ({item.Type}) - X:{item.X}, Y:{item.Y}");
}
}
private void btnAddPrintItem_Click(object sender, EventArgs e)
{
PrintItem newItem = new PrintItem
{
Name = "新打印项",
Type = PrintItemType.Text,
X = 10, Y = 10, Width = 50, Height = 10,
Content = "示例内容",
FontSize = 10
};
currentTemplate.PrintItems.Add(newItem);
UpdateTemplateInfo();
}
private void btnDeletePrintItem_Click(object sender, EventArgs e)
{
if (lstPrintItems.SelectedIndex >= 0)
{
currentTemplate.PrintItems.RemoveAt(lstPrintItems.SelectedIndex);
UpdateTemplateInfo();
}
}
private void lstPrintItems_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstPrintItems.SelectedIndex >= 0)
{
selectedItem = currentTemplate.PrintItems[lstPrintItems.SelectedIndex];
UpdatePrintItemProperties();
}
}
private void UpdatePrintItemProperties()
{
if (selectedItem == null) return;
txtItemName.Text = selectedItem.Name;
cmbItemType.SelectedItem = selectedItem.Type.ToString();
numX.Value = (decimal)selectedItem.X;
numY.Value = (decimal)selectedItem.Y;
numWidth.Value = (decimal)selectedItem.Width;
numHeight.Value = (decimal)selectedItem.Height;
txtContent.Text = selectedItem.Content;
txtDataSourceField.Text = selectedItem.DataSourceField;
cmbFontFamily.SelectedItem = selectedItem.FontFamily;
numFontSize.Value = (decimal)selectedItem.FontSize;
chkFontBold.Checked = selectedItem.FontStyle.HasFlag(FontStyle.Bold);
chkFontItalic.Checked = selectedItem.FontStyle.HasFlag(FontStyle.Italic);
chkFontUnderline.Checked = selectedItem.FontStyle.HasFlag(FontStyle.Underline);
cmbAlignment.SelectedItem = selectedItem.Alignment.ToString();
txtForeColor.Text = selectedItem.ForeColor;
txtBackColor.Text = selectedItem.BackColor;
numBorderWidth.Value = (decimal)selectedItem.BorderWidth;
txtBorderColor.Text = selectedItem.BorderColor;
numRotation.Value = (decimal)selectedItem.Rotation;
chkVisible.Checked = selectedItem.Visible;
}
private void SavePrintItemProperties()
{
if (selectedItem == null) return;
selectedItem.Name = txtItemName.Text;
selectedItem.Type = (PrintItemType)Enum.Parse(typeof(PrintItemType), cmbItemType.SelectedItem.ToString());
selectedItem.X = (float)numX.Value;
selectedItem.Y = (float)numY.Value;
selectedItem.Width = (float)numWidth.Value;
selectedItem.Height = (float)numHeight.Value;
selectedItem.Content = txtContent.Text;
selectedItem.DataSourceField = txtDataSourceField.Text;
selectedItem.FontFamily = cmbFontFamily.SelectedItem.ToString();
selectedItem.FontSize = (float)numFontSize.Value;
FontStyle style = FontStyle.Regular;
if (chkFontBold.Checked) style |= FontStyle.Bold;
if (chkFontItalic.Checked) style |= FontStyle.Italic;
if (chkFontUnderline.Checked) style |= FontStyle.Underline;
selectedItem.FontStyle = style;
selectedItem.Alignment = (StringAlignment)Enum.Parse(typeof(StringAlignment), cmbAlignment.SelectedItem.ToString());
selectedItem.ForeColor = txtForeColor.Text;
selectedItem.BackColor = txtBackColor.Text;
selectedItem.BorderWidth = (float)numBorderWidth.Value;
selectedItem.BorderColor = txtBorderColor.Text;
selectedItem.Rotation = (float)numRotation.Value;
selectedItem.Visible = chkVisible.Checked;
UpdateTemplateInfo();
}
private void btnSaveTemplate_Click(object sender, EventArgs e)
{
SavePrintItemProperties();
currentTemplate.TemplateName = txtTemplateName.Text;
currentTemplate.CompanyName = txtCompanyName.Text;
currentTemplate.ModifiedDate = DateTime.Now;
ExpressTemplateManager.SaveTemplate(currentTemplate);
MessageBox.Show("模板保存成功!", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void btnPreview_Click(object sender, EventArgs e)
{
SavePrintItemProperties();
PrintPreviewForm previewForm = new PrintPreviewForm(currentTemplate);
previewForm.ShowDialog();
}
#region Windows Form Designer generated code
private System.ComponentModel.IContainer components = null;
private TextBox txtTemplateName;
private Label label1;
private GroupBox groupBox1;
private TextBox txtCompanyName;
private Label label2;
private GroupBox groupBox2;
private NumericUpDown numPageWidth;
private Label label3;
private NumericUpDown numPageHeight;
private Label label4;
private GroupBox groupBox3;
private NumericUpDown numMarginLeft;
private Label label5;
private NumericUpDown numMarginTop;
private Label label6;
private NumericUpDown numMarginRight;
private Label label7;
private NumericUpDown numMarginBottom;
private GroupBox groupBox4;
private ListBox lstPrintItems;
private Button btnAddPrintItem;
private Button btnDeletePrintItem;
private GroupBox groupBox5;
private TextBox txtItemName;
private Label label8;
private ComboBox cmbItemType;
private Label label9;
private NumericUpDown numX;
private Label label10;
private NumericUpDown numY;
private Label label11;
private NumericUpDown numWidth;
private Label label12;
private NumericUpDown numHeight;
private Label label13;
private TextBox txtContent;
private Label label14;
private TextBox txtDataSourceField;
private Label label15;
private ComboBox cmbFontFamily;
private Label label16;
private NumericUpDown numFontSize;
private Label label17;
private CheckBox chkFontBold;
private CheckBox chkFontItalic;
private CheckBox chkFontUnderline;
private ComboBox cmbAlignment;
private Label label18;
private TextBox txtForeColor;
private Label label19;
private TextBox txtBackColor;
private Label label20;
private NumericUpDown numBorderWidth;
private Label label21;
private TextBox txtBorderColor;
private Label label22;
private NumericUpDown numRotation;
private Label label23;
private CheckBox chkVisible;
private Button btnSaveTemplate;
private Button btnPreview;
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.txtTemplateName = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.txtCompanyName = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.numPageWidth = new System.Windows.Forms.NumericUpDown();
this.label3 = new System.Windows.Forms.Label();
this.numPageHeight = new System.Windows.Forms.NumericUpDown();
this.label4 = new System.Windows.Forms.Label();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.numMarginBottom = new System.Windows.Forms.NumericUpDown();
this.label7 = new System.Windows.Forms.Label();
this.numMarginRight = new System.Windows.Forms.NumericUpDown();
this.label6 = new System.Windows.Forms.Label();
this.numMarginTop = new System.Windows.Forms.NumericUpDown();
this.label5 = new System.Windows.Forms.Label();
this.numMarginLeft = new System.Windows.Forms.NumericUpDown();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.btnDeletePrintItem = new System.Windows.Forms.Button();
this.btnAddPrintItem = new System.Windows.Forms.Button();
this.lstPrintItems = new System.Windows.Forms.ListBox();
this.groupBox5 = new System.Windows.Forms.GroupBox();
this.chkVisible = new System.Windows.Forms.CheckBox();
this.numRotation = new System.Windows.Forms.NumericUpDown();
this.label23 = new System.Windows.Forms.Label();
this.txtBorderColor = new System.Windows.Forms.TextBox();
this.label22 = new System.Windows.Forms.Label();
this.numBorderWidth = new System.Windows.Forms.NumericUpDown();
this.label21 = new System.Windows.Forms.Label();
this.txtBackColor = new System.Windows.Forms.TextBox();
this.label20 = new System.Windows.Forms.Label();
this.txtForeColor = new System.Windows.Forms.TextBox();
this.label19 = new System.Windows.Forms.Label();
this.cmbAlignment = new System.Windows.Forms.ComboBox();
this.label18 = new System.Windows.Forms.Label();
this.chkFontUnderline = new System.Windows.Forms.CheckBox();
this.chkFontItalic = new System.Windows.Forms.CheckBox();
this.chkFontBold = new System.Windows.Forms.CheckBox();
this.numFontSize = new System.Windows.Forms.NumericUpDown();
this.label17 = new System.Windows.Forms.Label();
this.cmbFontFamily = new System.Windows.Forms.ComboBox();
this.label16 = new System.Windows.Forms.Label();
this.txtDataSourceField = new System.Windows.Forms.TextBox();
this.label15 = new System.Windows.Forms.Label();
this.txtContent = new System.Windows.Forms.TextBox();
this.label14 = new System.Windows.Forms.Label();
this.numHeight = new System.Windows.Forms.NumericUpDown();
this.label13 = new System.Windows.Forms.Label();
this.numWidth = new System.Windows.Forms.NumericUpDown();
this.label12 = new System.Windows.Forms.Label();
this.numY = new System.Windows.Forms.NumericUpDown();
this.label11 = new System.Windows.Forms.Label();
this.numX = new System.Windows.Forms.NumericUpDown();
this.label10 = new System.Windows.Forms.Label();
this.cmbItemType = new System.Windows.Forms.ComboBox();
this.label9 = new System.Windows.Forms.Label();
this.txtItemName = new System.Windows.Forms.TextBox();
this.label8 = new System.Windows.Forms.Label();
this.btnSaveTemplate = new System.Windows.Forms.Button();
this.btnPreview = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numPageWidth)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numPageHeight)).BeginInit();
this.groupBox3.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numMarginBottom)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numMarginRight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numMarginTop)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numMarginLeft)).BeginInit();
this.groupBox4.SuspendLayout();
this.groupBox5.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numRotation)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numBorderWidth)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numFontSize)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numHeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numWidth)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numY)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numX)).BeginInit();
this.SuspendLayout();
// txtTemplateName
this.txtTemplateName.Location = new System.Drawing.Point(80, 20);
this.txtTemplateName.Name = "txtTemplateName";
this.txtTemplateName.Size = new System.Drawing.Size(200, 23);
this.txtTemplateName.TabIndex = 0;
// label1
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(20, 23);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(56, 13);
this.label1.TabIndex = 1;
this.label1.Text = "模板名称:";
// groupBox1
this.groupBox1.Controls.Add(this.txtCompanyName);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Location = new System.Drawing.Point(12, 50);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(300, 60);
this.groupBox1.TabIndex = 2;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "基本信息";
// txtCompanyName
this.txtCompanyName.Location = new System.Drawing.Point(80, 25);
this.txtCompanyName.Name = "txtCompanyName";
this.txtCompanyName.Size = new System.Drawing.Size(200, 23);
this.txtCompanyName.TabIndex = 1;
// label2
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(20, 28);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(56, 13);
this.label2.TabIndex = 0;
this.label2.Text = "快递公司:";
// groupBox2
this.groupBox2.Controls.Add(this.numPageHeight);
this.groupBox2.Controls.Add(this.label4);
this.groupBox2.Controls.Add(this.numPageWidth);
this.groupBox2.Controls.Add(this.label3);
this.groupBox2.Location = new System.Drawing.Point(12, 120);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(300, 80);
this.groupBox2.TabIndex = 3;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "页面设置";
// numPageWidth
this.numPageWidth.DecimalPlaces = 1;
this.numPageWidth.Location = new System.Drawing.Point(80, 25);
this.numPageWidth.Name = "numPageWidth";
this.numPageWidth.Size = new System.Drawing.Size(80, 23);
this.numPageWidth.TabIndex = 1;
this.numPageWidth.Value = new decimal(new int[] { 210, 0, 0, 0 });
// label3
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(20, 28);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(56, 13);
this.label3.TabIndex = 0;
this.label3.Text = "页面宽度:";
// numPageHeight
this.numPageHeight.DecimalPlaces = 1;
this.numPageHeight.Location = new System.Drawing.Point(200, 25);
this.numPageHeight.Name = "numPageHeight";
this.numPageHeight.Size = new System.Drawing.Size(80, 23);
this.numPageHeight.TabIndex = 3;
this.numPageHeight.Value = new decimal(new int[] { 297, 0, 0, 0 });
// label4
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(165, 28);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(32, 13);
this.label4.TabIndex = 2;
this.label4.Text = "高度:";
// groupBox3
this.groupBox3.Controls.Add(this.numMarginBottom);
this.groupBox3.Controls.Add(this.label7);
this.groupBox3.Controls.Add(this.numMarginRight);
this.groupBox3.Controls.Add(this.label6);
this.groupBox3.Controls.Add(this.numMarginTop);
this.groupBox3.Controls.Add(this.label5);
this.groupBox3.Controls.Add(this.numMarginLeft);
this.groupBox3.Location = new System.Drawing.Point(12, 210);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(300, 120);
this.groupBox3.TabIndex = 4;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "页边距";
// numMarginBottom
this.numMarginBottom.DecimalPlaces = 1;
this.numMarginBottom.Location = new System.Drawing.Point(200, 85);
this.numMarginBottom.Name = "numMarginBottom";
this.numMarginBottom.Size = new System.Drawing.Size(80, 23);
this.numMarginBottom.TabIndex = 7;
this.numMarginBottom.Value = new decimal(new int[] { 10, 0, 0, 0 });
// label7
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(165, 88);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(32, 13);
this.label7.TabIndex = 6;
this.label7.Text = "下边:";
// numMarginRight
this.numMarginRight.DecimalPlaces = 1;
this.numMarginRight.Location = new System.Drawing.Point(200, 55);
this.numMarginRight.Name = "numMarginRight";
this.numMarginRight.Size = new System.Drawing.Size(80, 23);
this.numMarginRight.TabIndex = 5;
this.numMarginRight.Value = new decimal(new int[] { 10, 0, 0, 0 });
// label6
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(165, 58);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(32, 13);
this.label6.TabIndex = 4;
this.label6.Text = "右边:";
// numMarginTop
this.numMarginTop.DecimalPlaces = 1;
this.numMarginTop.Location = new System.Drawing.Point(80, 55);
this.numMarginTop.Name = "numMarginTop";
this.numMarginTop.Size = new System.Drawing.Size(80, 23);
this.numMarginTop.TabIndex = 3;
this.numMarginTop.Value = new decimal(new int[] { 10, 0, 0, 0 });
// label5
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(20, 58);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(32, 13);
this.label5.TabIndex = 2;
this.label5.Text = "上边:";
// numMarginLeft
this.numMarginLeft.DecimalPlaces = 1;
this.numMarginLeft.Location = new System.Drawing.Point(80, 25);
this.numMarginLeft.Name = "numMarginLeft";
this.numMarginLeft.Size = new System.Drawing.Size(80, 23);
this.numMarginLeft.TabIndex = 1;
this.numMarginLeft.Value = new decimal(new int[] { 10, 0, 0, 0 });
// groupBox4
this.groupBox4.Controls.Add(this.btnDeletePrintItem);
this.groupBox4.Controls.Add(this.btnAddPrintItem);
this.groupBox4.Controls.Add(this.lstPrintItems);
this.groupBox4.Location = new System.Drawing.Point(12, 340);
this.groupBox4.Name = "groupBox4";
this.groupBox4.Size = new System.Drawing.Size(300, 200);
this.groupBox4.TabIndex = 5;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "打印项";
// btnDeletePrintItem
this.btnDeletePrintItem.Location = new System.Drawing.Point(180, 160);
this.btnDeletePrintItem.Name = "btnDeletePrintItem";
this.btnDeletePrintItem.Size = new System.Drawing.Size(100, 25);
this.btnDeletePrintItem.TabIndex = 2;
this.btnDeletePrintItem.Text = "删除";
this.btnDeletePrintItem.UseVisualStyleBackColor = true;
this.btnDeletePrintItem.Click += new System.EventHandler(this.btnDeletePrintItem_Click);
// btnAddPrintItem
this.btnAddPrintItem.Location = new System.Drawing.Point(20, 160);
this.btnAddPrintItem.Name = "btnAddPrintItem";
this.btnAddPrintItem.Size = new System.Drawing.Size(100, 25);
this.btnAddPrintItem.TabIndex = 1;
this.btnAddPrintItem.Text = "添加";
this.btnAddPrintItem.UseVisualStyleBackColor = true;
this.btnAddPrintItem.Click += new System.EventHandler(this.btnAddPrintItem_Click);
// lstPrintItems
this.lstPrintItems.FormattingEnabled = true;
this.lstPrintItems.Location = new System.Drawing.Point(20, 25);
this.lstPrintItems.Name = "lstPrintItems";
this.lstPrintItems.Size = new System.Drawing.Size(260, 130);
this.lstPrintItems.TabIndex = 0;
this.lstPrintItems.SelectedIndexChanged += new System.EventHandler(this.lstPrintItems_SelectedIndexChanged);
// groupBox5
this.groupBox5.Controls.Add(this.chkVisible);
this.groupBox5.Controls.Add(this.numRotation);
this.groupBox5.Controls.Add(this.label23);
this.groupBox5.Controls.Add(this.txtBorderColor);
this.groupBox5.Controls.Add(this.label22);
this.groupBox5.Controls.Add(this.numBorderWidth);
this.groupBox5.Controls.Add(this.label21);
this.groupBox5.Controls.Add(this.txtBackColor);
this.groupBox5.Controls.Add(this.label20);
this.groupBox5.Controls.Add(this.txtForeColor);
this.groupBox5.Controls.Add(this.label19);
this.groupBox5.Controls.Add(this.cmbAlignment);
this.groupBox5.Controls.Add(this.label18);
this.groupBox5.Controls.Add(this.chkFontUnderline);
this.groupBox5.Controls.Add(this.chkFontItalic);
this.groupBox5.Controls.Add(this.chkFontBold);
this.groupBox5.Controls.Add(this.numFontSize);
this.groupBox5.Controls.Add(this.label17);
this.groupBox5.Controls.Add(this.cmbFontFamily);
this.groupBox5.Controls.Add(this.label16);
this.groupBox5.Controls.Add(this.txtDataSourceField);
this.groupBox5.Controls.Add(this.label15);
this.groupBox5.Controls.Add(this.txtContent);
this.groupBox5.Controls.Add(this.label14);
this.groupBox5.Controls.Add(this.numHeight);
this.groupBox5.Controls.Add(this.label13);
this.groupBox5.Controls.Add(this.numWidth);
this.groupBox5.Controls.Add(this.label12);
this.groupBox5.Controls.Add(this.numY);
this.groupBox5.Controls.Add(this.label11);
this.groupBox5.Controls.Add(this.numX);
this.groupBox5.Controls.Add(this.label10);
this.groupBox5.Controls.Add(this.cmbItemType);
this.groupBox5.Controls.Add(this.label9);
this.groupBox5.Controls.Add(this.txtItemName);
this.groupBox5.Controls.Add(this.label8);
this.groupBox5.Location = new System.Drawing.Point(320, 12);
this.groupBox5.Name = "groupBox5";
this.groupBox5.Size = new System.Drawing.Size(400, 528);
this.groupBox5.TabIndex = 6;
this.groupBox5.TabStop = false;
this.groupBox5.Text = "打印项属性";
// chkVisible
this.chkVisible.AutoSize = true;
this.chkVisible.Location = new System.Drawing.Point(300, 490);
this.chkVisible.Name = "chkVisible";
this.chkVisible.Size = new System.Drawing.Size(78, 17);
this.chkVisible.TabIndex = 42;
this.chkVisible.Text = "可见";
this.chkVisible.UseVisualStyleBackColor = true;
// numRotation
this.numRotation.DecimalPlaces = 1;
this.numRotation.Location = new System.Drawing.Point(300, 460);
this.numRotation.Name = "numRotation";
this.numRotation.Size = new System.Drawing.Size(80, 23);
this.numRotation.TabIndex = 41;
// label23
this.label23.AutoSize = true;
this.label23.Location = new System.Drawing.Point(250, 463);
this.label23.Name = "label23";
this.label23.Size = new System.Drawing.Size(44, 13);
this.label23.TabIndex = 40;
this.label23.Text = "旋转角度:";
// txtBorderColor
this.txtBorderColor.Location = new System.Drawing.Point(300, 430);
this.txtBorderColor.Name = "txtBorderColor";
this.txtBorderColor.Size = new System.Drawing.Size(80, 23);
this.txtBorderColor.TabIndex = 39;
this.txtBorderColor.Text = "#000000";
// label22
this.label22.AutoSize = true;
this.label22.Location = new System.Drawing.Point(250, 433);
this.label22.Name = "label22";
this.label22.Size = new System.Drawing.Size(44, 13);
this.label22.TabIndex = 38;
this.label22.Text = "边框颜色:";
// numBorderWidth
this.numBorderWidth.DecimalPlaces = 1;
this.numBorderWidth.Location = new System.Drawing.Point(300, 400);
this.numBorderWidth.Name = "numBorderWidth";
this.numBorderWidth.Size = new System.Drawing.Size(80, 23);
this.numBorderWidth.TabIndex = 37;
// label21
this.label21.AutoSize = true;
this.label21.Location = new System.Drawing.Point(250, 403);
this.label21.Name = "label21";
this.label21.Size = new System.Drawing.Size(44, 13);
this.label21.TabIndex = 36;
this.label21.Text = "边框宽度:";
// txtBackColor
this.txtBackColor.Location = new System.Drawing.Point(300, 370);
this.txtBackColor.Name = "txtBackColor";
this.txtBackColor.Size = new System.Drawing.Size(80, 23);
this.txtBackColor.TabIndex = 35;
this.txtBackColor.Text = "#FFFFFF";
// label20
this.label20.AutoSize = true;
this.label20.Location = new System.Drawing.Point(250, 373);
this.label20.Name = "label20";
this.label20.Size = new System.Drawing.Size(44, 13);
this.label20.TabIndex = 34;
this.label20.Text = "背景颜色:";
// txtForeColor
this.txtForeColor.Location = new System.Drawing.Point(300, 340);
this.txtForeColor.Name = "txtForeColor";
this.txtForeColor.Size = new System.Drawing.Size(80, 23);
this.txtForeColor.TabIndex = 33;
this.txtForeColor.Text = "#000000";
// label19
this.label19.AutoSize = true;
this.label19.Location = new System.Drawing.Point(250, 343);
this.label19.Name = "label19";
this.label19.Size = new System.Drawing.Size(44, 13);
this.label19.TabIndex = 34;
this.label19.Text = "文字颜色:";
// cmbAlignment
this.cmbAlignment.FormattingEnabled = true;
this.cmbAlignment.Items.AddRange(new object[] { "Near", "Center", "Far" });
this.cmbAlignment.Location = new System.Drawing.Point(300, 310);
this.cmbAlignment.Name = "cmbAlignment";
this.cmbAlignment.Size = new System.Drawing.Size(80, 21);
this.cmbAlignment.TabIndex = 32;
// label18
this.label18.AutoSize = true;
this.label18.Location = new System.Drawing.Point(250, 313);
this.label18.Name = "label18";
this.label18.Size = new System.Drawing.Size(44, 13);
this.label18.TabIndex = 31;
this.label18.Text = "对齐方式:";
// chkFontUnderline
this.chkFontUnderline.AutoSize = true;
this.chkFontUnderline.Location = new System.Drawing.Point(300, 280);
this.chkFontUnderline.Name = "chkFontUnderline";
this.chkFontUnderline.Size = new System.Drawing.Size(60, 17);
this.chkFontUnderline.TabIndex = 30;
this.chkFontUnderline.Text = "下划线";
this.chkFontUnderline.UseVisualStyleBackColor = true;
// chkFontItalic
this.chkFontItalic.AutoSize = true;
this.chkFontItalic.Location = new System.Drawing.Point(240, 280);
this.chkFontItalic.Name = "chkFontItalic";
this.chkFontItalic.Size = new System.Drawing.Size(48, 17);
this.chkFontItalic.TabIndex = 29;
this.chkFontItalic.Text = "斜体";
this.chkFontItalic.UseVisualStyleBackColor = true;
// chkFontBold
this.chkFontBold.AutoSize = true;
this.chkFontBold.Location = new System.Drawing.Point(180, 280);
this.chkFontBold.Name = "chkFontBold";
this.chkFontBold.Size = new System.Drawing.Size(48, 17);
this.chkFontBold.TabIndex = 28;
this.chkFontBold.Text = "粗体";
this.chkFontBold.UseVisualStyleBackColor = true;
// numFontSize
this.numFontSize.DecimalPlaces = 1;
this.numFontSize.Location = new System.Drawing.Point(300, 250);
this.numFontSize.Name = "numFontSize";
this.numFontSize.Size = new System.Drawing.Size(80, 23);
this.numFontSize.TabIndex = 27;
this.numFontSize.Value = new decimal(new int[] { 10, 0, 0, 0 });
// label17
this.label17.AutoSize = true;
this.label17.Location = new System.Drawing.Point(250, 253);
this.label17.Name = "label17";
this.label17.Size = new System.Drawing.Size(44, 13);
this.label17.TabIndex = 26;
this.label17.Text = "字体大小:";
// cmbFontFamily
this.cmbFontFamily.FormattingEnabled = true;
this.cmbFontFamily.Items.AddRange(new object[] { "宋体", "黑体", "微软雅黑", "Arial", "Times New Roman" });
this.cmbFontFamily.Location = new System.Drawing.Point(300, 220);
this.cmbFontFamily.Name = "cmbFontFamily";
this.cmbFontFamily.Size = new System.Drawing.Size(80, 21);
this.cmbFontFamily.TabIndex = 25;
// label16
this.label16.AutoSize = true;
this.label16.Location = new System.Drawing.Point(250, 223);
this.label16.Name = "label16";
this.label16.Size = new System.Drawing.Size(44, 13);
this.label16.TabIndex = 24;
this.label16.Text = "字体名称:";
// txtDataSourceField
this.txtDataSourceField.Location = new System.Drawing.Point(300, 190);
this.txtDataSourceField.Name = "txtDataSourceField";
this.txtDataSourceField.Size = new System.Drawing.Size(80, 23);
this.txtDataSourceField.TabIndex = 23;
// label15
this.label15.AutoSize = true;
this.label15.Location = new System.Drawing.Point(250, 193);
this.label15.Name = "label15";
this.label15.Size = new System.Drawing.Size(44, 13);
this.label15.TabIndex = 22;
this.label15.Text = "数据源字段:";
// txtContent
this.txtContent.Location = new System.Drawing.Point(300, 160);
this.txtContent.Name = "txtContent";
this.txtContent.Size = new System.Drawing.Size(80, 23);
this.txtContent.TabIndex = 21;
// label14
this.label14.AutoSize = true;
this.label14.Location = new System.Drawing.Point(250, 163);
this.label14.Name = "label14";
this.label14.Size = new System.Drawing.Size(44, 13);
this.label14.TabIndex = 20;
this.label14.Text = "内容:";
// numHeight
this.numHeight.DecimalPlaces = 1;
this.numHeight.Location = new System.Drawing.Point(300, 130);
this.numHeight.Name = "numHeight";
this.numHeight.Size = new System.Drawing.Size(80, 23);
this.numHeight.TabIndex = 19;
this.numHeight.Value = new decimal(new int[] { 10, 0, 0, 0 });
// label13
this.label13.AutoSize = true;
this.label13.Location = new System.Drawing.Point(250, 133);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(44, 13);
this.label13.TabIndex = 18;
this.label13.Text = "高度:";
// numWidth
this.numWidth.DecimalPlaces = 1;
this.numWidth.Location = new System.Drawing.Point(300, 100);
this.numWidth.Name = "numWidth";
this.numWidth.Size = new System.Drawing.Size(80, 23);
this.numWidth.TabIndex = 17;
this.numWidth.Value = new decimal(new int[] { 50, 0, 0, 0 });
// label12
this.label12.AutoSize = true;
this.label12.Location = new System.Drawing.Point(250, 103);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(44, 13);
this.label12.TabIndex = 16;
this.label12.Text = "宽度:";
// numY
this.numY.DecimalPlaces = 1;
this.numY.Location = new System.Drawing.Point(300, 70);
this.numY.Name = "numY";
this.numY.Size = new System.Drawing.Size(80, 23);
this.numY.TabIndex = 15;
// label11
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(250, 73);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(32, 13);
this.label11.TabIndex = 14;
this.label11.Text = "Y坐标:";
// numX
this.numX.DecimalPlaces = 1;
this.numX.Location = new System.Drawing.Point(300, 40);
this.numX.Name = "numX";
this.numX.Size = new System.Drawing.Size(80, 23);
this.numX.TabIndex = 13;
// label10
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(250, 43);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(32, 13);
this.label10.TabIndex = 12;
this.label10.Text = "X坐标:";
// cmbItemType
this.cmbItemType.FormattingEnabled = true;
this.cmbItemType.Items.AddRange(new object[] { "Text", "Barcode", "QRCode", "Image", "Line", "Rectangle" });
this.cmbItemType.Location = new System.Drawing.Point(300, 10);
this.cmbItemType.Name = "cmbItemType";
this.cmbItemType.Size = new System.Drawing.Size(80, 21);
this.cmbItemType.TabIndex = 11;
// label9
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(250, 13);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(32, 13);
this.label9.TabIndex = 10;
this.label9.Text = "类型:";
// txtItemName
this.txtItemName.Location = new System.Drawing.Point(80, 10);
this.txtItemName.Name = "txtItemName";
this.txtItemName.Size = new System.Drawing.Size(150, 23);
this.txtItemName.TabIndex = 9;
// label8
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(20, 13);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(56, 13);
this.label8.TabIndex = 8;
this.label8.Text = "项目名称:";
// btnSaveTemplate
this.btnSaveTemplate.Location = new System.Drawing.Point(650, 550);
this.btnSaveTemplate.Name = "btnSaveTemplate";
this.btnSaveTemplate.Size = new System.Drawing.Size(100, 30);
this.btnSaveTemplate.TabIndex = 7;
this.btnSaveTemplate.Text = "保存模板";
this.btnSaveTemplate.UseVisualStyleBackColor = true;
this.btnSaveTemplate.Click += new System.EventHandler(this.btnSaveTemplate_Click);
// btnPreview
this.btnPreview.Location = new System.Drawing.Point(520, 550);
this.btnPreview.Name = "btnPreview";
this.btnPreview.Size = new System.Drawing.Size(100, 30);
this.btnPreview.TabIndex = 8;
this.btnPreview.Text = "预览";
this.btnPreview.UseVisualStyleBackColor = true;
this.btnPreview.Click += new System.EventHandler(this.btnPreview_Click);
// TemplateEditorForm
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(732, 592);
this.Controls.Add(this.btnPreview);
this.Controls.Add(this.btnSaveTemplate);
this.Controls.Add(this.groupBox5);
this.Controls.Add(this.groupBox4);
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.label1);
this.Controls.Add(this.txtTemplateName);
this.Name = "TemplateEditorForm";
this.Text = "模板编辑器";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numPageWidth)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numPageHeight)).EndInit();
this.groupBox3.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numMarginBottom)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numMarginRight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numMarginTop)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numMarginLeft)).EndInit();
this.groupBox4.ResumeLayout(false);
this.groupBox5.ResumeLayout(false);
this.groupBox5.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.numRotation)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numBorderWidth)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numFontSize)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numHeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numWidth)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numY)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numX)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
2.7 打印预览窗体 (PrintPreviewForm.cs)
csharp
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;
namespace ExpressPrintSystem
{
public partial class PrintPreviewForm : Form
{
private ExpressTemplate template;
private PrintDocument printDocument;
private int currentPage = 0;
private Bitmap previewBitmap;
public PrintPreviewForm(ExpressTemplate template)
{
InitializeComponent();
this.template = template;
this.printDocument = new PrintDocument();
this.printDocument.PrintPage += PrintDocument_PrintPage;
GeneratePreview();
}
private void GeneratePreview()
{
// 创建预览位图
float dpi = 96f; // 屏幕DPI
float mmToPixel = dpi / 25.4f; // 毫米转像素
int width = (int)(template.PageSize.Width * mmToPixel);
int height = (int)(template.PageSize.Height * mmToPixel);
previewBitmap = new Bitmap(width, height);
using Graphics g = Graphics.FromImage(previewBitmap);
g.Clear(Color.White);
g.PageUnit = GraphicsUnit.Millimeter;
// 绘制页边距
g.TranslateTransform(template.Margin.Left, template.Margin.Top);
// 绘制打印项
foreach (var item in template.PrintItems)
{
if (!item.Visible) continue;
DrawPrintItem(g, item, item.Content);
}
// 显示预览
pictureBoxPreview.Image = previewBitmap;
lblPageInfo.Text = $"页面 1 / 1";
}
private void DrawPrintItem(Graphics g, PrintItem item, string content)
{
// 设置字体
FontStyle fontStyle = item.FontStyle;
using Font font = new Font(item.FontFamily, item.FontSize, (System.Drawing.FontStyle)fontStyle);
// 设置画刷
using SolidBrush brush = new SolidBrush(ColorTranslator.FromHtml(item.ForeColor));
// 设置边框
using Pen pen = new Pen(ColorTranslator.FromHtml(item.BorderColor), item.BorderWidth);
// 创建矩形区域
RectangleF rect = new RectangleF(item.X, item.Y, item.Width, item.Height);
// 根据类型绘制
switch (item.Type)
{
case PrintItemType.Text:
StringFormat sf = new StringFormat();
sf.Alignment = (StringAlignment)item.Alignment;
sf.LineAlignment = StringAlignment.Center;
g.DrawString(content, font, brush, rect, sf);
break;
case PrintItemType.Barcode:
try
{
var writer = new ZXing.BarcodeWriter
{
Format = ZXing.BarcodeFormat.CODE_128,
Options = new ZXing.Common.EncodingOptions
{
Width = (int)(item.Width * 3.78f),
Height = (int)(item.Height * 3.78f),
Margin = 1
}
};
using Bitmap barcode = writer.Write(content);
g.DrawImage(barcode, rect);
}
catch
{
g.DrawString(content, font, brush, rect);
}
break;
case PrintItemType.QRCode:
try
{
var writer = new ZXing.BarcodeWriter
{
Format = ZXing.BarcodeFormat.QR_CODE,
Options = new ZXing.Common.EncodingOptions
{
Width = (int)(item.Width * 3.78f),
Height = (int)(item.Height * 3.78f),
Margin = 1
}
};
using Bitmap qrcode = writer.Write(content);
g.DrawImage(qrcode, rect);
}
catch
{
g.DrawString("QR:" + content, font, brush, rect);
}
break;
case PrintItemType.Rectangle:
g.DrawRectangle(pen, rect.X, rect.Y, rect.Width, rect.Height);
if (item.BackColor != "#FFFFFF")
{
using SolidBrush backBrush = new SolidBrush(ColorTranslator.FromHtml(item.BackColor));
g.FillRectangle(backBrush, rect);
}
break;
case PrintItemType.Line:
g.DrawLine(pen, rect.X, rect.Y, rect.X + rect.Width, rect.Y + rect.Height);
break;
}
}
private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
{
// 与PrintEngine相同的打印逻辑
Graphics g = e.Graphics;
g.PageUnit = GraphicsUnit.Millimeter;
g.TranslateTransform(template.Margin.Left, template.Margin.Top);
foreach (var item in template.PrintItems)
{
if (!item.Visible) continue;
DrawPrintItem(g, item, item.Content);
}
e.HasMorePages = false;
}
#region Windows Form Designer generated code
private System.ComponentModel.IContainer components = null;
private PictureBox pictureBoxPreview;
private Panel panelControls;
private Button btnPrint;
private Button btnClose;
private Label lblPageInfo;
private Button btnZoomIn;
private Button btnZoomOut;
private Button btnFitToWindow;
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.pictureBoxPreview = new System.Windows.Forms.PictureBox();
this.panelControls = new System.Windows.Forms.Panel();
this.btnFitToWindow = new System.Windows.Forms.Button();
this.btnZoomOut = new System.Windows.Forms.Button();
this.btnZoomIn = new System.Windows.Forms.Button();
this.lblPageInfo = new System.Windows.Forms.Label();
this.btnPrint = new System.Windows.Forms.Button();
this.btnClose = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxPreview)).BeginInit();
this.panelControls.SuspendLayout();
this.SuspendLayout();
// pictureBoxPreview
this.pictureBoxPreview.BackColor = System.Drawing.Color.White;
this.pictureBoxPreview.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.pictureBoxPreview.Location = new System.Drawing.Point(12, 12);
this.pictureBoxPreview.Name = "pictureBoxPreview";
this.pictureBoxPreview.Size = new System.Drawing.Size(600, 800);
this.pictureBoxPreview.TabIndex = 0;
this.pictureBoxPreview.TabStop = false;
// panelControls
this.panelControls.Controls.Add(this.btnFitToWindow);
this.panelControls.Controls.Add(this.btnZoomOut);
this.panelControls.Controls.Add(this.btnZoomIn);
this.panelControls.Controls.Add(this.lblPageInfo);
this.panelControls.Controls.Add(this.btnPrint);
this.panelControls.Controls.Add(this.btnClose);
this.panelControls.Dock = System.Windows.Forms.DockStyle.Bottom;
this.panelControls.Location = new System.Drawing.Point(0, 824);
this.panelControls.Name = "panelControls";
this.panelControls.Size = new System.Drawing.Size(624, 50);
this.panelControls.TabIndex = 1;
// btnFitToWindow
this.btnFitToWindow.Location = new System.Drawing.Point(300, 10);
this.btnFitToWindow.Name = "btnFitToWindow";
this.btnFitToWindow.Size = new System.Drawing.Size(80, 30);
this.btnFitToWindow.TabIndex = 5;
this.btnFitToWindow.Text = "适应窗口";
this.btnFitToWindow.UseVisualStyleBackColor = true;
// btnZoomOut
this.btnZoomOut.Location = new System.Drawing.Point(220, 10);
this.btnZoomOut.Name = "btnZoomOut";
this.btnZoomOut.Size = new System.Drawing.Size(60, 30);
this.btnZoomOut.TabIndex = 4;
this.btnZoomOut.Text = "缩小";
this.btnZoomOut.UseVisualStyleBackColor = true;
// btnZoomIn
this.btnZoomIn.Location = new System.Drawing.Point(140, 10);
this.btnZoomIn.Name = "btnZoomIn";
this.btnZoomIn.Size = new System.Drawing.Size(60, 30);
this.btnZoomIn.TabIndex = 3;
this.btnZoomIn.Text = "放大";
this.btnZoomIn.UseVisualStyleBackColor = true;
// lblPageInfo
this.lblPageInfo.AutoSize = true;
this.lblPageInfo.Location = new System.Drawing.Point(20, 17);
this.lblPageInfo.Name = "lblPageInfo";
this.lblPageInfo.Size = new System.Drawing.Size(47, 13);
this.lblPageInfo.TabIndex = 2;
this.lblPageInfo.Text = "页面 1 / 1";
// btnPrint
this.btnPrint.Location = new System.Drawing.Point(480, 10);
this.btnPrint.Name = "btnPrint";
this.btnPrint.Size = new System.Drawing.Size(60, 30);
this.btnPrint.TabIndex = 1;
this.btnPrint.Text = "打印";
this.btnPrint.UseVisualStyleBackColor = true;
this.btnPrint.Click += new System.EventHandler(this.btnPrint_Click);
// btnClose
this.btnClose.Location = new System.Drawing.Point(550, 10);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(60, 30);
this.btnClose.TabIndex = 0;
this.btnClose.Text = "关闭";
this.btnClose.UseVisualStyleBackColor = true;
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
// PrintPreviewForm
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(624, 874);
this.Controls.Add(this.panelControls);
this.Controls.Add(this.pictureBoxPreview);
this.Name = "PrintPreviewForm";
this.Text = "打印预览";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxPreview)).EndInit();
this.panelControls.ResumeLayout(false);
this.panelControls.PerformLayout();
this.ResumeLayout(false);
}
private void btnPrint_Click(object sender, EventArgs e)
{
PrintDialog printDialog = new PrintDialog();
printDialog.Document = printDocument;
if (printDialog.ShowDialog() == DialogResult.OK)
{
printDocument.Print();
}
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
#endregion
}
}
2.8 数据导入窗体 (DataImportForm.cs)
csharp
using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using ClosedXML.Excel;
namespace ExpressPrintSystem
{
public partial class DataImportForm : Form
{
private DataTable importedData = new DataTable();
private List<Dictionary<string, object>> orderDataList = new List<Dictionary<string, object>>();
public DataImportForm()
{
InitializeComponent();
LoadFieldMappings();
}
private void LoadFieldMappings()
{
// 加载字段映射
cmbReceiverName.Items.AddRange(new string[] { "ReceiverName", "收件人姓名", "姓名" });
cmbReceiverPhone.Items.AddRange(new string[] { "ReceiverPhone", "收件人电话", "电话" });
cmbReceiverAddress.Items.AddRange(new string[] { "ReceiverAddress", "收件人地址", "地址" });
cmbWaybillNo.Items.AddRange(new string[] { "WaybillNo", "运单号", "单号" });
cmbSenderName.Items.AddRange(new string[] { "SenderName", "寄件人姓名", "寄件人" });
cmbSenderPhone.Items.AddRange(new string[] { "SenderPhone", "寄件人电话", "寄件电话" });
cmbSenderAddress.Items.AddRange(new string[] { "SenderAddress", "寄件人地址", "寄件地址" });
cmbGoodsName.Items.AddRange(new string[] { "GoodsName", "物品名称", "商品" });
cmbWeight.Items.AddRange(new string[] { "Weight", "重量", "重量(kg)" });
cmbRemark.Items.AddRange(new string[] { "Remark", "备注", "说明" });
}
private void btnBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Excel文件|*.xlsx;*.xls|CSV文件|*.csv|所有文件|*.*";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
txtFilePath.Text = openFileDialog.FileName;
LoadDataFromFile(openFileDialog.FileName);
}
}
private void LoadDataFromFile(string filePath)
{
try
{
if (filePath.EndsWith(".xlsx") || filePath.EndsWith(".xls"))
{
LoadExcelData(filePath);
}
else if (filePath.EndsWith(".csv"))
{
LoadCsvData(filePath);
}
// 显示数据预览
dataGridViewPreview.DataSource = importedData;
lblRowCount.Text = $"共 {importedData.Rows.Count} 行数据";
}
catch (Exception ex)
{
MessageBox.Show($"加载文件失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadExcelData(string filePath)
{
using XLWorkbook workbook = new XLWorkbook(filePath);
IXLWorksheet worksheet = workbook.Worksheet(1);
importedData.Clear();
// 获取列标题
var firstRow = worksheet.Row(1);
foreach (var cell in firstRow.Cells())
{
importedData.Columns.Add(cell.Value.ToString());
}
// 获取数据行
var rows = worksheet.RowsUsed();
foreach (var row in rows)
{
if (row.RowNumber() == 1) continue; // 跳过标题行
DataRow dataRow = importedData.NewRow();
int colIndex = 0;
foreach (var cell in row.Cells(1, importedData.Columns.Count))
{
dataRow[colIndex++] = cell.Value.ToString();
}
importedData.Rows.Add(dataRow);
}
}
private void LoadCsvData(string filePath)
{
string[] lines = File.ReadAllLines(filePath);
if (lines.Length == 0) return;
importedData.Clear();
// 第一行是标题
string[] headers = lines[0].Split(',');
foreach (string header in headers)
{
importedData.Columns.Add(header);
}
// 数据行
for (int i = 1; i < lines.Length; i++)
{
string[] values = lines[i].Split(',');
DataRow row = importedData.NewRow();
for (int j = 0; j < Math.Min(values.Length, headers.Length); j++)
{
row[j] = values[j];
}
importedData.Rows.Add(row);
}
}
private void btnImport_Click(object sender, EventArgs e)
{
if (importedData.Rows.Count == 0)
{
MessageBox.Show("没有可导入的数据!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
// 转换数据为订单列表
orderDataList.Clear();
foreach (DataRow row in importedData.Rows)
{
Dictionary<string, object> order = new Dictionary<string, object>();
// 根据字段映射添加数据
AddMappedField(order, cmbReceiverName.SelectedItem?.ToString(), row);
AddMappedField(order, cmbReceiverPhone.SelectedItem?.ToString(), row);
AddMappedField(order, cmbReceiverAddress.SelectedItem?.ToString(), row);
AddMappedField(order, cmbWaybillNo.SelectedItem?.ToString(), row);
AddMappedField(order, cmbSenderName.SelectedItem?.ToString(), row);
AddMappedField(order, cmbSenderPhone.SelectedItem?.ToString(), row);
AddMappedField(order, cmbSenderAddress.SelectedItem?.ToString(), row);
AddMappedField(order, cmbGoodsName.SelectedItem?.ToString(), row);
AddMappedField(order, cmbWeight.SelectedItem?.ToString(), row);
AddMappedField(order, cmbRemark.SelectedItem?.ToString(), row);
orderDataList.Add(order);
}
MessageBox.Show($"成功导入 {orderDataList.Count} 条订单数据!", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.DialogResult = DialogResult.OK;
this.Close();
}
private void AddMappedField(Dictionary<string, object> order, string mapping, DataRow row)
{
if (string.IsNullOrEmpty(mapping)) return;
// 查找对应的列
for (int i = 0; i < importedData.Columns.Count; i++)
{
if (importedData.Columns[i].ColumnName.Equals(mapping, StringComparison.OrdinalIgnoreCase))
{
order[mapping] = row[i].ToString();
break;
}
}
}
#region Windows Form Designer generated code
private System.ComponentModel.IContainer components = null;
private TextBox txtFilePath;
private Button btnBrowse;
private Label label1;
private GroupBox groupBox1;
private Label label11;
private ComboBox cmbRemark;
private Label label10;
private ComboBox cmbWeight;
private Label label9;
private ComboBox cmbGoodsName;
private Label label8;
private ComboBox cmbSenderAddress;
private Label label7;
private ComboBox cmbSenderPhone;
private Label label6;
private ComboBox cmbSenderName;
private Label label5;
private ComboBox cmbWaybillNo;
private Label label4;
private ComboBox cmbReceiverAddress;
private Label label3;
private ComboBox cmbReceiverPhone;
private Label label2;
private ComboBox cmbReceiverName;
private GroupBox groupBox2;
private DataGridView dataGridViewPreview;
private Label lblRowCount;
private Button btnImport;
private Button btnCancel;
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.txtFilePath = new System.Windows.Forms.TextBox();
this.btnBrowse = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.cmbRemark = new System.Windows.Forms.ComboBox();
this.label11 = new System.Windows.Forms.Label();
this.cmbWeight = new System.Windows.Forms.ComboBox();
this.label10 = new System.Windows.Forms.Label();
this.cmbGoodsName = new System.Windows.Forms.ComboBox();
this.label9 = new System.Windows.Forms.Label();
this.cmbSenderAddress = new System.Windows.Forms.ComboBox();
this.label8 = new System.Windows.Forms.Label();
this.cmbSenderPhone = new System.Windows.Forms.ComboBox();
this.label7 = new System.Windows.Forms.Label();
this.cmbSenderName = new System.Windows.Forms.ComboBox();
this.label6 = new System.Windows.Forms.Label();
this.cmbWaybillNo = new System.Windows.Forms.ComboBox();
this.label5 = new System.Windows.Forms.Label();
this.cmbReceiverAddress = new System.Windows.Forms.ComboBox();
this.label4 = new System.Windows.Forms.Label();
this.cmbReceiverPhone = new System.Windows.Forms.ComboBox();
this.label3 = new System.Windows.Forms.Label();
this.cmbReceiverName = new System.Windows.Forms.ComboBox();
this.label2 = new System.Windows.Forms.Label();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.lblRowCount = new System.Windows.Forms.Label();
this.dataGridViewPreview = new System.Windows.Forms.DataGridView();
this.btnImport = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridViewPreview)).BeginInit();
this.SuspendLayout();
// txtFilePath
this.txtFilePath.Location = new System.Drawing.Point(80, 20);
this.txtFilePath.Name = "txtFilePath";
this.txtFilePath.Size = new System.Drawing.Size(400, 23);
this.txtFilePath.TabIndex = 0;
// btnBrowse
this.btnBrowse.Location = new System.Drawing.Point(490, 18);
this.btnBrowse.Name = "btnBrowse";
this.btnBrowse.Size = new System.Drawing.Size(75, 23);
this.btnBrowse.TabIndex = 1;
this.btnBrowse.Text = "浏览...";
this.btnBrowse.UseVisualStyleBackColor = true;
this.btnBrowse.Click += new System.EventHandler(this.btnBrowse_Click);
// label1
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(20, 23);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(56, 13);
this.label1.TabIndex = 2;
this.label1.Text = "文件路径:";
// groupBox1
this.groupBox1.Controls.Add(this.cmbRemark);
this.groupBox1.Controls.Add(this.label11);
this.groupBox1.Controls.Add(this.cmbWeight);
this.groupBox1.Controls.Add(this.label10);
this.groupBox1.Controls.Add(this.cmbGoodsName);
this.groupBox1.Controls.Add(this.label9);
this.groupBox1.Controls.Add(this.cmbSenderAddress);
this.groupBox1.Controls.Add(this.label8);
this.groupBox1.Controls.Add(this.cmbSenderPhone);
this.groupBox1.Controls.Add(this.label7);
this.groupBox1.Controls.Add(this.cmbSenderName);
this.groupBox1.Controls.Add(this.label6);
this.groupBox1.Controls.Add(this.cmbWaybillNo);
this.groupBox1.Controls.Add(this.label5);
this.groupBox1.Controls.Add(this.cmbReceiverAddress);
this.groupBox1.Controls.Add(this.label4);
this.groupBox1.Controls.Add(this.cmbReceiverPhone);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.cmbReceiverName);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Location = new System.Drawing.Point(12, 50);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(553, 150);
this.groupBox1.TabIndex = 3;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "字段映射";
// cmbRemark
this.cmbRemark.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbRemark.FormattingEnabled = true;
this.cmbRemark.Location = new System.Drawing.Point(450, 115);
this.cmbRemark.Name = "cmbRemark";
this.cmbRemark.Size = new System.Drawing.Size(90, 21);
this.cmbRemark.TabIndex = 21;
// label11
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(400, 118);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(44, 13);
this.label11.TabIndex = 20;
this.label11.Text = "备注字段:";
// cmbWeight
this.cmbWeight.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbWeight.FormattingEnabled = true;
this.cmbWeight.Location = new System.Drawing.Point(300, 115);
this.cmbWeight.Name = "cmbWeight";
this.cmbWeight.Size = new System.Drawing.Size(90, 21);
this.cmbWeight.TabIndex = 19;
// label10
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(250, 118);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(44, 13);
this.label10.TabIndex = 18;
this.label10.Text = "重量字段:";
// cmbGoodsName
this.cmbGoodsName.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbGoodsName.FormattingEnabled = true;
this.cmbGoodsName.Location = new System.Drawing.Point(150, 115);
this.cmbGoodsName.Name = "cmbGoodsName";
this.cmbGoodsName.Size = new System.Drawing.Size(90, 21);
this.cmbGoodsName.TabIndex = 17;
// label9
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(20, 118);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(56, 13);
this.label9.TabIndex = 16;
this.label9.Text = "物品名称字段:";
// cmbSenderAddress
this.cmbSenderAddress.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbSenderAddress.FormattingEnabled = true;
this.cmbSenderAddress.Location = new System.Drawing.Point(450, 85);
this.cmbSenderAddress.Name = "cmbSenderAddress";
this.cmbSenderAddress.Size = new System.Drawing.Size(90, 21);
this.cmbSenderAddress.TabIndex = 15;
// label8
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(400, 88);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(56, 13);
this.label8.TabIndex = 14;
this.label8.Text = "寄件地址字段:";
// cmbSenderPhone
this.cmbSenderPhone.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbSenderPhone.FormattingEnabled = true;
this.cmbSenderPhone.Location = new System.Drawing.Point(300, 85);
this.cmbSenderPhone.Name = "cmbSenderPhone";
this.cmbSenderPhone.Size = new System.Drawing.Size(90, 21);
this.cmbSenderPhone.TabIndex = 13;
// label7
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(250, 88);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(56, 13);
this.label7.TabIndex = 12;
this.label7.Text = "寄件电话字段:";
// cmbSenderName
this.cmbSenderName.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbSenderName.FormattingEnabled = true;
this.cmbSenderName.Location = new System.Drawing.Point(150, 85);
this.cmbSenderName.Name = "cmbSenderName";
this.cmbSenderName.Size = new System.Drawing.Size(90, 21);
this.cmbSenderName.TabIndex = 11;
// label6
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(20, 88);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(56, 13);
this.label6.TabIndex = 10;
this.label6.Text = "寄件人姓名字段:";
// cmbWaybillNo
this.cmbWaybillNo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbWaybillNo.FormattingEnabled = true;
this.cmbWaybillNo.Location = new System.Drawing.Point(450, 55);
this.cmbWaybillNo.Name = "cmbWaybillNo";
this.cmbWaybillNo.Size = new System.Drawing.Size(90, 21);
this.cmbWaybillNo.TabIndex = 9;
// label5
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(400, 58);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(56, 13);
this.label5.TabIndex = 8;
this.label5.Text = "运单号字段:";
// cmbReceiverAddress
this.cmbReceiverAddress.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbReceiverAddress.FormattingEnabled = true;
this.cmbReceiverAddress.Location = new System.Drawing.Point(300, 55);
this.cmbReceiverAddress.Name = "cmbReceiverAddress";
this.cmbReceiverAddress.Size = new System.Drawing.Size(90, 21);
this.cmbReceiverAddress.TabIndex = 7;
// label4
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(250, 58);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(56, 13);
this.label4.TabIndex = 6;
this.label4.Text = "收件地址字段:";
// cmbReceiverPhone
this.cmbReceiverPhone.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbReceiverPhone.FormattingEnabled = true;
this.cmbReceiverPhone.Location = new System.Drawing.Point(150, 55);
this.cmbReceiverPhone.Name = "cmbReceiverPhone";
this.cmbReceiverPhone.Size = new System.Drawing.Size(90, 21);
this.cmbReceiverPhone.TabIndex = 5;
// label3
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(20, 58);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(56, 13);
this.label3.TabIndex = 4;
this.label3.Text = "收件电话字段:";
// cmbReceiverName
this.cmbReceiverName.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbReceiverName.FormattingEnabled = true;
this.cmbReceiverName.Location = new System.Drawing.Point(150, 25);
this.cmbReceiverName.Name = "cmbReceiverName";
this.cmbReceiverName.Size = new System.Drawing.Size(90, 21);
this.cmbReceiverName.TabIndex = 3;
// label2
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(20, 28);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(56, 13);
this.label2.TabIndex = 2;
this.label2.Text = "收件人姓名字段:";
// groupBox2
this.groupBox2.Controls.Add(this.lblRowCount);
this.groupBox2.Controls.Add(this.dataGridViewPreview);
this.groupBox2.Location = new System.Drawing.Point(12, 210);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(553, 300);
this.groupBox2.TabIndex = 4;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "数据预览";
// lblRowCount
this.lblRowCount.AutoSize = true;
this.lblRowCount.Location = new System.Drawing.Point(20, 275);
this.lblRowCount.Name = "lblRowCount";
this.lblRowCount.Size = new System.Drawing.Size(47, 13);
this.lblRowCount.TabIndex = 1;
this.lblRowCount.Text = "共 0 行数据";
// dataGridViewPreview
this.dataGridViewPreview.AllowUserToAddRows = false;
this.dataGridViewPreview.AllowUserToDeleteRows = false;
this.dataGridViewPreview.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridViewPreview.Location = new System.Drawing.Point(20, 25);
this.dataGridViewPreview.Name = "dataGridViewPreview";
this.dataGridViewPreview.ReadOnly = true;
this.dataGridViewPreview.Size = new System.Drawing.Size(513, 240);
this.dataGridViewPreview.TabIndex = 0;
// btnImport
this.btnImport.Location = new System.Drawing.Point(400, 520);
this.btnImport.Name = "btnImport";
this.btnImport.Size = new System.Drawing.Size(80, 30);
this.btnImport.TabIndex = 5;
this.btnImport.Text = "导入";
this.btnImport.UseVisualStyleBackColor = true;
this.btnImport.Click += new System.EventHandler(this.btnImport_Click);
// btnCancel
this.btnCancel.Location = new System.Drawing.Point(490, 520);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(80, 30);
this.btnCancel.TabIndex = 6;
this.btnCancel.Text = "取消";
this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
// DataImportForm
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(577, 562);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnImport);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.label1);
this.Controls.Add(this.btnBrowse);
this.Controls.Add(this.txtFilePath);
this.Name = "DataImportForm";
this.Text = "数据导入";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridViewPreview)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}
#endregion
}
}
三、程序入口 (Program.cs)
csharp
using System;
using System.Windows.Forms;
namespace ExpressPrintSystem
{
internal static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
参考代码 快递单打印系统(万能套打系统) www.youwenfan.com/contentcsv/116210.html
四、功能特点
万能套打 :支持自定义模板,可适配任何快递公司的面单
多模板管理 :内置顺丰、圆通等常用模板,支持自定义
可视化编辑器 :拖拽调整打印项位置,所见即所得
批量打印 :支持从Excel/CSV导入大量订单数据
多种打印项 :文本、条形码、二维码、图片、线条、矩形
数据源绑定 :支持 {字段名} 动态替换
打印预览 :实时预览打印效果
打印机选择 :支持选择指定打印机
配置保存:模板以XML格式保存,便于备份和迁移
五、使用方法
5.1 快速开始
- 运行程序,选择快递模板
- 导入Excel订单数据
- 点击"打印预览"查看效果
- 点击"打印"输出到打印机
5.2 自定义模板
- 点击"模板编辑器"
- 添加打印项(文本、条形码、二维码等)
- 调整位置和大小
- 保存模板
5.3 Excel数据格式
csv
ReceiverName,ReceiverPhone,ReceiverAddress,SenderName,SenderPhone,SenderAddress,WaybillNo,GoodsName,Weight,Remark
张三,13800138000,"北京市朝阳区建国路100号",李四,13900139000,"上海市浦东新区张江高科技园区",SF1234567890,电子产品,2.5kg,易碎品