C# NPOI读取excel

在.NET中,我们操作excel一般都是使用NPOI这个组件,它成熟稳定又好用。下面的代码记录了项目中的一段使用NPOI读取excel的功能的实现:

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

IWorkbook hssfwb;
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
    if (fileName.IndexOf(".xlsx") > 0) // 2007版本
        hssfwb = new XSSFWorkbook(fs);
    else // if (fileName.IndexOf(".xls") > 0) // 2003版本
        hssfwb = new HSSFWorkbook(fs); 
}

ISheet sheet = hssfwb.GetSheetAt(0); // 或 ISheet sheet = hssfwb.GetSheet("Arkusz1");
for (int row = 1; row <= sheet.LastRowNum; row++)
{
    if (sheet.GetRow(row) != null) //null is when the row only contains empty cells
    {
        var s = string.Format("Row {0} = {1}", row, sheet.GetRow(row).GetCell(0).StringCellValue);
    }
}

对DTO的理解 

DTO是一个类,相当于ViewModel,通过restful api接口传输

DTO贯穿在request的过程中,viewmodel也差不多

使用的时候,通过automapper实体映射工具和数据库实体进行转换

DTO是后端不同模块之间传输数据用,不涉及前端和视图

C# 执行CMD命令

在.NET的项目开发中有时需要调用系统(Windows)命令,可以使用下面的函数来调用:

private static string InvokeCmd(string cmdArgs)
{
    string Tstr = "";
    Process p = new Process();
    p.StartInfo.FileName = "cmd.exe";
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardInput = true;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.RedirectStandardError = true;
    p.StartInfo.CreateNoWindow = true;
    p.Start();
    p.StandardInput.WriteLine(cmdArgs);
    p.StandardInput.WriteLine("exit");
    Tstr = p.StandardOutput.ReadToEnd();
    p.Close();
    return Tstr;
}

该函数经过项目测试,没有问题。

C# 使用TTS播放声音

C# 使用Windows系统自带的TTS播放声音,以下代码基于.NET Framework4.0

// 定义成全局的,因为每次创建实例需要一定的时间,会造成播放延迟
private dynamic spVoice = Activator.CreateInstance(Type.GetTypeFromProgID("SAPI.SpVoice"));

//调用的时候
this.spVoice.Speak("你好,我是TTS合成语音");

C# WinForm设置dataGridView表头字体大小

C# WinForm中,设置dataGridView控件表头字体的大小:

var font = new Font(dataGridView1.ColumnHeadersDefaultCellStyle.Font.FontFamily, dataGridView1.ColumnHeadersDefaultCellStyle.Font.Size + 8);
dataGridView1.ColumnHeadersDefaultCellStyle.Font = font;

示例

// 构造函数
public HomeForm()
{
        InitializeComponent();
        //奇数行的单元格的背景色为黄绿色
        dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.LightGray;
        var font = new Font(dataGridView1.ColumnHeadersDefaultCellStyle.Font.FontFamily, dataGridView1.ColumnHeadersDefaultCellStyle.Font.Size + 8);
        dataGridView1.ColumnHeadersDefaultCellStyle.Font = font;
        BindCombox();
        BindDataGrid();
        dataGridView1.Columns[0].Width = 300;
        this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
}

C# WinForm 自动关闭 定时关闭 MessageBox

C# WinForm 的开发中,有时需要一个可以自动关闭的弹出框,下面的代码是自动关闭或定时关闭的一个MessageBox的实现:

public class AutoClosingMessageBox
{
    System.Threading.Timer _timeoutTimer;
    string _caption;
    DialogResult _result;
    DialogResult _timerResult;
    AutoClosingMessageBox(string text, string caption, int timeout, MessageBoxButtons buttons = MessageBoxButtons.OK, DialogResult timerResult = DialogResult.None)
    {
        _caption = caption;
        _timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
            null, timeout, System.Threading.Timeout.Infinite);
        _timerResult = timerResult;
        using (_timeoutTimer)
            _result = MessageBox.Show(text, caption, buttons);
    }
    public static DialogResult Show(string text, string caption, int timeout, MessageBoxButtons buttons = MessageBoxButtons.OK, DialogResult timerResult = DialogResult.None)
    {
        return new AutoClosingMessageBox(text, caption, timeout, buttons, timerResult)._result;
    }
    void OnTimerElapsed(object state)
    {
        IntPtr mbWnd = FindWindow("#32770", _caption); // lpClassName is #32770 for MessageBox
        if (mbWnd != IntPtr.Zero)
            SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
        _timeoutTimer.Dispose();
        _result = _timerResult;
    }
    const int WM_CLOSE = 0x0010;
    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
}

用法:

AutoClosingMessageBox.Show("Text", "Caption", 1000);

返回值 

var userResult = AutoClosingMessageBox.Show("Yes or No?", "Caption", 1000, MessageBoxButtons.YesNo);if(userResult == System.Windows.Forms.DialogResult.Yes) {
// do something}

也可以通过Nuget安装这个包

Install-Package AutoClosingMessageBox