第02章-环境配置与项目创建

第二章:环境配置与项目创建

2.1 Visual Studio项目创建

2.1.1 创建Windows Forms项目

方式1:使用Visual Studio 2022

步骤1:启动Visual Studio

文件 → 新建 → 项目

步骤2:选择项目模板

搜索框输入:Windows Forms
选择:Windows Forms App (.NET Framework) 或 Windows Forms App (.NET 6/7/8)
点击:下一步

步骤3:配置项目

项目名称:ReoGridDemo
位置:D:\Projects\
解决方案名称:ReoGridDemo
框架:.NET Framework 4.7.2 或 .NET 6.0
点击:创建

方式2:使用.NET CLI

# 创建新的Windows Forms项目
dotnet new winforms -n ReoGridDemo -f net6.0

# 进入项目目录
cd ReoGridDemo

# 打开项目
dotnet sln add ReoGridDemo.csproj

2.1.2 创建WPF项目

使用Visual Studio创建

文件 → 新建 → 项目
搜索:WPF Application
选择:WPF App (.NET Framework) 或 WPF App (.NET 6/7/8)
配置项目名称和位置
点击:创建

使用CLI创建

# 创建WPF项目
dotnet new wpf -n ReoGridWpfDemo -f net6.0

cd ReoGridWpfDemo

2.1.3 项目结构说明

Windows Forms项目结构

ReoGridDemo/
├── Properties/              # 项目属性
│   ├── AssemblyInfo.cs     # 程序集信息
│   └── Resources.resx      # 资源文件
├── Form1.cs                # 主窗体代码
├── Form1.Designer.cs       # 设计器代码
├── Form1.resx             # 窗体资源
├── Program.cs             # 程序入口
├── App.config             # 应用配置
└── ReoGridDemo.csproj     # 项目文件

WPF项目结构

ReoGridWpfDemo/
├── Properties/
│   └── AssemblyInfo.cs
├── MainWindow.xaml        # 主窗口XAML
├── MainWindow.xaml.cs     # 主窗口代码
├── App.xaml              # 应用程序XAML
├── App.xaml.cs           # 应用程序代码
└── ReoGridWpfDemo.csproj # 项目文件

2.2 安装ReoGrid

2.2.1 通过NuGet包管理器安装(推荐)

方式1:可视化界面

右键点击项目 → 管理NuGet程序包
切换到"浏览"选项卡
搜索:unvell.ReoGrid.dll
选择包并点击"安装"
接受许可协议
等待安装完成

方式2:包管理器控制台

# 打开包管理器控制台
工具 → NuGet包管理器 → 包管理器控制台

# 安装Windows Forms版本
Install-Package unvell.ReoGrid.dll

# 安装WPF版本
Install-Package unvell.ReoGrid.WPF

# 安装特定版本
Install-Package unvell.ReoGrid.dll -Version 3.3.0

方式3:.NET CLI

# Windows Forms版本
dotnet add package unvell.ReoGrid.dll

# WPF版本
dotnet add package unvell.ReoGrid.WPF

# 指定版本
dotnet add package unvell.ReoGrid.dll --version 3.3.0

2.2.2 手动引用DLL文件

步骤1:下载DLL文件

访问:https://github.com/unvell/ReoGrid/releases
下载最新版本的Release包
解压到本地目录,如:D:\Libraries\ReoGrid\

步骤2:添加引用

在解决方案资源管理器中:
右键点击"引用" → "添加引用"
点击"浏览"按钮
选择以下文件:
- unvell.ReoGrid.dll
- unvell.Common.dll (如果存在)
点击"确定"

步骤3:验证引用

// 在代码文件中添加using语句
using unvell.ReoGrid;

// 尝试创建控件实例
var grid = new ReoGridControl();

2.2.3 从源码编译

步骤1:克隆仓库

# 克隆ReoGrid仓库
git clone https://github.com/unvell/ReoGrid.git
cd ReoGrid

步骤2:打开解决方案

使用Visual Studio打开:
ReoGrid\ReoGrid.sln

步骤3:选择配置并编译

1. 在顶部工具栏选择配置:
   - Release(发布版本)
   - Debug(调试版本)

2. 选择平台:
   - Any CPU
   - x86
   - x64

3. 编译:
   生成 → 生成解决方案 (Ctrl+Shift+B)

步骤4:查找编译输出

编译完成后,DLL文件位于:
ReoGrid\bin\Release\unvell.ReoGrid.dll

2.3 配置项目

2.3.1 添加ReoGrid控件到工具箱

方式1:自动添加(推荐)

NuGet安装后,控件会自动添加到工具箱的"ReoGrid"分组中。

方式2:手动添加

步骤:
1. 打开工具箱(视图 → 工具箱)
2. 右键点击工具箱空白处
3. 选择"选择项"
4. 点击"浏览"按钮
5. 选择unvell.ReoGrid.dll文件
6. 点击"确定"

2.3.2 Windows Forms项目配置

方式1:使用设计器添加控件

// Form1.Designer.cs 自动生成的代码
private void InitializeComponent()
{
    this.reoGridControl1 = new unvell.ReoGrid.ReoGridControl();
    this.SuspendLayout();
    // 
    // reoGridControl1
    // 
    this.reoGridControl1.BackColor = System.Drawing.Color.White;
    this.reoGridControl1.Dock = System.Windows.Forms.DockStyle.Fill;
    this.reoGridControl1.Location = new System.Drawing.Point(0, 0);
    this.reoGridControl1.Name = "reoGridControl1";
    this.reoGridControl1.Size = new System.Drawing.Size(800, 450);
    this.reoGridControl1.TabIndex = 0;
    // 
    // Form1
    // 
    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.reoGridControl1);
    this.Name = "Form1";
    this.Text = "ReoGrid演示";
    this.ResumeLayout(false);
}

private unvell.ReoGrid.ReoGridControl reoGridControl1;

方式2:代码动态创建

using System;
using System.Windows.Forms;
using unvell.ReoGrid;

namespace ReoGridDemo
{
    public partial class Form1 : Form
    {
        private ReoGridControl grid;
        
        public Form1()
        {
            InitializeComponent();
            InitializeGrid();
        }
        
        private void InitializeGrid()
        {
            // 创建ReoGrid控件
            grid = new ReoGridControl
            {
                Dock = DockStyle.Fill,
                BackColor = System.Drawing.Color.White
            };
            
            // 添加到窗体
            this.Controls.Add(grid);
            
            // 设置为前端显示
            grid.BringToFront();
        }
    }
}

2.3.3 WPF项目配置

XAML配置

<Window x:Class="ReoGridWpfDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:rg="clr-namespace:unvell.ReoGrid.WPF;assembly=unvell.ReoGrid.WPF"
        Title="ReoGrid WPF Demo" Height="450" Width="800">
    <Grid>
        <rg:WorksheetControl x:Name="grid"/>
    </Grid>
</Window>

代码后台配置

using System.Windows;
using unvell.ReoGrid;

namespace ReoGridWpfDemo
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            InitializeGrid();
        }
        
        private void InitializeGrid()
        {
            // 获取当前工作表
            var worksheet = grid.Worksheet;
            
            // 初始化数据
            worksheet["A1"] = "姓名";
            worksheet["B1"] = "年龄";
            
            // 设置样式
            worksheet.SetRangeStyles("A1:B1", new WorksheetRangeStyle
            {
                Flag = PlainStyleFlag.FontBold,
                Bold = true
            });
        }
    }
}

2.4 基础配置

2.4.1 应用程序配置文件

App.config示例

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>
    
    <appSettings>
        <!-- ReoGrid相关配置 -->
        <add key="ReoGrid.DefaultRowHeight" value="20"/>
        <add key="ReoGrid.DefaultColumnWidth" value="80"/>
        <add key="ReoGrid.EnableFormulaCalculation" value="true"/>
    </appSettings>
</configuration>

2.4.2 全局设置

using unvell.ReoGrid;
using unvell.ReoGrid.Data;

public class GlobalSettings
{
    public static void ConfigureReoGrid(ReoGridControl grid)
    {
        // 启用公式自动计算
        grid.SetSettings(WorkbookSettings.Formula_AutoCalculate, true);
        
        // 启用自动格式化
        grid.SetSettings(WorkbookSettings.Edit_AutoFormatCell, true);
        
        // 允许编辑
        grid.SetSettings(WorkbookSettings.Edit_Readonly, false);
        
        // 显示网格线
        grid.SetSettings(WorkbookSettings.View_ShowGridLine, true);
        
        // 显示行列头
        grid.SetSettings(WorkbookSettings.View_ShowRowHeader, true);
        grid.SetSettings(WorkbookSettings.View_ShowColumnHeader, true);
        
        // 允许选择
        grid.SetSettings(WorkbookSettings.Edit_AllowSelectRange, true);
        
        // 允许拖放
        grid.SetSettings(WorkbookSettings.Edit_DragSelectionToMoveCells, true);
    }
}

2.4.3 工作表初始化

using unvell.ReoGrid;

public class WorksheetInitializer
{
    public static void Initialize(Worksheet sheet)
    {
        // 设置工作表名称
        sheet.Name = "数据表1";
        
        // 设置默认行高和列宽
        sheet.SetRowsHeight(0, sheet.RowCount, 25);
        sheet.SetColumnsWidth(0, sheet.ColumnCount, 100);
        
        // 设置默认字体
        sheet.SetRangeStyles(RangePosition.EntireRange, new WorksheetRangeStyle
        {
            Flag = PlainStyleFlag.FontName | PlainStyleFlag.FontSize,
            FontName = "微软雅黑",
            FontSize = 10
        });
        
        // 冻结首行
        sheet.FreezeToCell(1, 0);
    }
}

2.5 项目结构规划

2.5.1 推荐的项目结构

ReoGridDemo/
├── Forms/                  # 窗体目录
│   ├── MainForm.cs        # 主窗体
│   ├── DataEntryForm.cs   # 数据录入窗体
│   └── ReportForm.cs      # 报表窗体
│
├── Models/                 # 数据模型
│   ├── Employee.cs        # 员工模型
│   └── Department.cs      # 部门模型
│
├── Services/               # 业务服务
│   ├── DataService.cs     # 数据服务
│   └── ExportService.cs   # 导出服务
│
├── Utils/                  # 工具类
│   ├── ReoGridHelper.cs   # ReoGrid辅助类
│   └── StyleHelper.cs     # 样式辅助类
│
├── Resources/              # 资源文件
│   ├── Icons/             # 图标
│   └── Templates/         # 模板文件
│
└── App.config             # 配置文件

2.5.2 辅助类示例

ReoGridHelper.cs

using System;
using System.Drawing;
using unvell.ReoGrid;
using unvell.ReoGrid.Data;

namespace ReoGridDemo.Utils
{
    public static class ReoGridHelper
    {
        /// <summary>
        /// 设置标题行样式
        /// </summary>
        public static void SetHeaderStyle(Worksheet sheet, string range)
        {
            sheet.SetRangeStyles(range, new WorksheetRangeStyle
            {
                Flag = PlainStyleFlag.BackColor | 
                       PlainStyleFlag.FontBold | 
                       PlainStyleFlag.HorizontalAlign,
                BackColor = Color.FromArgb(79, 129, 189),
                Bold = true,
                HAlign = ReoGridHorAlign.Center
            });
        }
        
        /// <summary>
        /// 设置交替行颜色
        /// </summary>
        public static void SetAlternateRowColors(Worksheet sheet, 
            int startRow, int endRow, int startCol, int endCol)
        {
            for (int row = startRow; row <= endRow; row++)
            {
                Color bgColor = row % 2 == 0 
                    ? Color.White 
                    : Color.FromArgb(242, 242, 242);
                
                sheet.SetRangeStyles(new RangePosition(row, startCol, 1, endCol - startCol + 1),
                    new WorksheetRangeStyle
                    {
                        Flag = PlainStyleFlag.BackColor,
                        BackColor = bgColor
                    });
            }
        }
        
        /// <summary>
        /// 自动调整列宽
        /// </summary>
        public static void AutoFitColumns(Worksheet sheet, int startCol, int endCol)
        {
            for (int col = startCol; col <= endCol; col++)
            {
                sheet.AutoFitColumnWidth(col);
            }
        }
        
        /// <summary>
        /// 快速填充数据
        /// </summary>
        public static void FillData<T>(Worksheet sheet, 
            int startRow, int startCol, T[,] data)
        {
            int rows = data.GetLength(0);
            int cols = data.GetLength(1);
            
            for (int r = 0; r < rows; r++)
            {
                for (int c = 0; c < cols; c++)
                {
                    sheet[startRow + r, startCol + c] = data[r, c];
                }
            }
        }
    }
}

StyleHelper.cs

using System.Drawing;
using unvell.ReoGrid.Data;

namespace ReoGridDemo.Utils
{
    public static class StyleHelper
    {
        // 预定义样式
        public static class Styles
        {
            public static WorksheetRangeStyle Header => new WorksheetRangeStyle
            {
                Flag = PlainStyleFlag.BackColor | PlainStyleFlag.FontBold | 
                       PlainStyleFlag.FontColor | PlainStyleFlag.HorizontalAlign,
                BackColor = Color.FromArgb(68, 114, 196),
                FontColor = Color.White,
                Bold = true,
                HAlign = ReoGridHorAlign.Center
            };
            
            public static WorksheetRangeStyle Currency => new WorksheetRangeStyle
            {
                Flag = PlainStyleFlag.DataFormat,
                DataFormat = CellDataFormatFlag.Currency
            };
            
            public static WorksheetRangeStyle Percentage => new WorksheetRangeStyle
            {
                Flag = PlainStyleFlag.DataFormat,
                DataFormat = CellDataFormatFlag.Percent
            };
            
            public static WorksheetRangeStyle Date => new WorksheetRangeStyle
            {
                Flag = PlainStyleFlag.DataFormat,
                DataFormat = CellDataFormatFlag.DateTime
            };
        }
        
        /// <summary>
        /// 创建边框样式
        /// </summary>
        public static WorksheetRangeStyle CreateBorderStyle(Color color, 
            BorderLineStyle style = BorderLineStyle.Solid)
        {
            return new WorksheetRangeStyle
            {
                Flag = PlainStyleFlag.Border,
                Border = new RangeBorderStyle
                {
                    Left = new BorderStyle { Color = color, Style = style },
                    Top = new BorderStyle { Color = color, Style = style },
                    Right = new BorderStyle { Color = color, Style = style },
                    Bottom = new BorderStyle { Color = color, Style = style }
                }
            };
        }
    }
}

2.6 常见问题与解决方案

2.6.1 安装问题

问题1:NuGet包安装失败

原因:

  • 网络连接问题
  • NuGet源配置错误
  • 包版本不兼容

解决方案:

# 清除NuGet缓存
dotnet nuget locals all --clear

# 使用国内镜像源
# 工具 → 选项 → NuGet包管理器 → 程序包源
# 添加源:
# 名称:Nuget China
# 源:https://nuget.cdn.azure.cn/v3/index.json

# 重新安装
Install-Package unvell.ReoGrid.dll -Source "Nuget China"

问题2:找不到程序集引用

错误信息:

未能加载文件或程序集"unvell.ReoGrid"或它的某一个依赖项

解决方案:

<!-- 在.csproj中添加 -->
<ItemGroup>
    <Reference Include="unvell.ReoGrid">
        <HintPath>..\packages\unvell.ReoGrid.dll.3.3.0\lib\net40\unvell.ReoGrid.dll</HintPath>
        <Private>True</Private>
    </Reference>
</ItemGroup>

2.6.2 编译问题

问题1:目标框架不兼容

错误信息:

此包不兼容.NET Framework 4.5

解决方案:

<!-- 修改项目文件中的目标框架 -->
<TargetFramework>net472</TargetFramework>
<!-- 或 -->
<TargetFramework>net6.0-windows</TargetFramework>

问题2:缺少依赖项

解决方案:

# 恢复所有NuGet包
dotnet restore

# 或在Visual Studio中
右键解决方案 → 还原NuGet程序包

2.6.3 运行时问题

问题1:控件不显示

原因:

  • 控件被其他控件遮挡
  • Dock属性设置不正确
  • 未正确初始化

解决方案:

private void FixControlDisplay()
{
    // 确保控件可见
    grid.Visible = true;
    
    // 调整Z序
    grid.BringToFront();
    
    // 设置正确的Dock
    grid.Dock = DockStyle.Fill;
    
    // 强制刷新
    grid.Invalidate();
    this.PerformLayout();
}

问题2:中文显示乱码

解决方案:

// 设置默认字体支持中文
var sheet = grid.CurrentWorksheet;
sheet.SetRangeStyles(RangePosition.EntireRange, new WorksheetRangeStyle
{
    Flag = PlainStyleFlag.FontName,
    FontName = "微软雅黑"  // 或 "宋体"、"SimSun"
});

2.7 验证安装

2.7.1 创建测试程序

using System;
using System.Windows.Forms;
using unvell.ReoGrid;

namespace InstallationTest
{
    public class TestForm : Form
    {
        private ReoGridControl grid;
        
        public TestForm()
        {
            this.Text = "ReoGrid安装验证";
            this.Size = new System.Drawing.Size(800, 600);
            
            // 创建控件
            grid = new ReoGridControl();
            grid.Dock = DockStyle.Fill;
            this.Controls.Add(grid);
            
            // 测试功能
            TestBasicFeatures();
        }
        
        private void TestBasicFeatures()
        {
            var sheet = grid.CurrentWorksheet;
            
            try
            {
                // 测试1:写入数据
                sheet["A1"] = "测试成功!";
                sheet["A2"] = DateTime.Now;
                sheet["A3"] = 123.456;
                
                // 测试2:设置样式
                sheet.SetRangeStyles("A1", new WorksheetRangeStyle
                {
                    Flag = PlainStyleFlag.FontSize | PlainStyleFlag.FontColor,
                    FontSize = 14,
                    FontColor = System.Drawing.Color.Green
                });
                
                // 测试3:公式计算
                sheet["B1"] = 10;
                sheet["B2"] = 20;
                sheet["B3"] = "=B1+B2";
                
                MessageBox.Show(
                    "ReoGrid安装成功!\n所有功能测试通过。",
                    "验证成功",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information
                );
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    $"测试失败:{ex.Message}",
                    "验证失败",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error
                );
            }
        }
        
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new TestForm());
        }
    }
}

2.7.2 功能清单验证

public class FeatureVerification
{
    public static void VerifyAllFeatures(ReoGridControl grid)
    {
        var sheet = grid.CurrentWorksheet;
        var results = new System.Text.StringBuilder();
        
        // 1. 数据读写
        try
        {
            sheet["A1"] = "测试";
            var value = sheet["A1"];
            results.AppendLine("✓ 数据读写功能正常");
        }
        catch { results.AppendLine("✗ 数据读写功能异常"); }
        
        // 2. 样式设置
        try
        {
            sheet.SetRangeStyles("A1", new WorksheetRangeStyle());
            results.AppendLine("✓ 样式设置功能正常");
        }
        catch { results.AppendLine("✗ 样式设置功能异常"); }
        
        // 3. 公式计算
        try
        {
            sheet["B1"] = "=1+1";
            var result = sheet["B1"];
            results.AppendLine("✓ 公式计算功能正常");
        }
        catch { results.AppendLine("✗ 公式计算功能异常"); }
        
        // 4. 行列操作
        try
        {
            sheet.InsertRows(0, 1);
            sheet.DeleteRows(0, 1);
            results.AppendLine("✓ 行列操作功能正常");
        }
        catch { results.AppendLine("✗ 行列操作功能异常"); }
        
        // 5. 单元格合并
        try
        {
            sheet.MergeRange("C1:E1");
            sheet.UnmergeRange("C1:E1");
            results.AppendLine("✓ 单元格合并功能正常");
        }
        catch { results.AppendLine("✗ 单元格合并功能异常"); }
        
        MessageBox.Show(results.ToString(), "功能验证结果");
    }
}

2.8 最佳实践

2.8.1 项目配置建议

<!-- .csproj配置建议 -->
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net6.0-windows</TargetFramework>
    <UseWindowsForms>true</UseWindowsForms>
    <Nullable>enable</Nullable>
    <PlatformTarget>AnyCPU</PlatformTarget>
    
    <!-- 性能优化 -->
    <Prefer32Bit>false</Prefer32Bit>
    <Optimize>true</Optimize>
    
    <!-- 调试设置 -->
    <DebugType>portable</DebugType>
  </PropertyGroup>
  
  <ItemGroup>
    <PackageReference Include="unvell.ReoGrid.dll" Version="3.3.0" />
  </ItemGroup>
</Project>

2.8.2 初始化模板

using System;
using System.Windows.Forms;
using unvell.ReoGrid;
using unvell.ReoGrid.Data;

namespace ReoGridTemplate
{
    public class BaseReoGridForm : Form
    {
        protected ReoGridControl Grid { get; private set; }
        
        protected BaseReoGridForm()
        {
            InitializeComponent();
            InitializeGrid();
            ConfigureGrid();
        }
        
        private void InitializeComponent()
        {
            this.Size = new System.Drawing.Size(1024, 768);
            this.StartPosition = FormStartPosition.CenterScreen;
        }
        
        private void InitializeGrid()
        {
            Grid = new ReoGridControl
            {
                Dock = DockStyle.Fill,
                BackColor = System.Drawing.Color.White
            };
            
            this.Controls.Add(Grid);
        }
        
        protected virtual void ConfigureGrid()
        {
            // 基本设置
            Grid.SetSettings(WorkbookSettings.Formula_AutoCalculate, true);
            Grid.SetSettings(WorkbookSettings.Edit_AutoFormatCell, true);
            Grid.SetSettings(WorkbookSettings.View_ShowGridLine, true);
            
            // 默认样式
            var sheet = Grid.CurrentWorksheet;
            sheet.SetRangeStyles(RangePosition.EntireRange, 
                new WorksheetRangeStyle
                {
                    Flag = PlainStyleFlag.FontName | PlainStyleFlag.FontSize,
                    FontName = "微软雅黑",
                    FontSize = 10
                });
        }
        
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            LoadData();
        }
        
        protected virtual void LoadData()
        {
            // 子类实现具体的数据加载逻辑
        }
    }
}

2.9 本章小结

✅ 本章学习内容

  1. 项目创建

    • Windows Forms项目创建
    • WPF项目创建
    • 项目结构说明
  2. ReoGrid安装

    • NuGet包管理器安装
    • 手动引用DLL
    • 源码编译
  3. 项目配置

    • 控件添加到工具箱
    • Windows Forms配置
    • WPF项目配置
  4. 基础配置

    • 全局设置
    • 工作表初始化
    • 项目结构规划
  5. 问题解决

    • 常见安装问题
    • 编译问题
    • 运行时问题
  6. 验证与最佳实践

    • 安装验证
    • 功能测试
    • 项目模板

📚 下一章预告

在第三章中,我们将深入学习:

  • ReoGrid的核心架构
  • Workbook和Worksheet概念
  • 单元格与区域模型
  • 数据流与事件机制
  • 渲染引擎原理

💡 实践建议

  1. 完成环境搭建:按照本章步骤完成项目创建和配置
  2. 运行测试程序:验证ReoGrid功能是否正常
  3. 创建项目模板:建立自己的项目模板,方便后续使用
  4. 熟悉工具:掌握Visual Studio和NuGet的基本使用

🔗 参考资源


准备好了吗?让我们在第三章深入理解ReoGrid的核心架构!

posted @ 2025-12-31 14:06  我才是银古  阅读(7)  评论(0)    收藏  举报