C#读取和写入Word文档、Excel表格、文本文档(txt)

// (1)读取文档路径
string pathFileName = Path.Combine(AbConfigUtil.ConfigPath(),"text.txt"); //AbConfigUtil.ConfigPath() 可以采用其他的方式 Assembly.GetCallingAssembly().FolderPath() 输出文件夹路径  /bin/Debug
// (2) 点选获取文件路径
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = "数据文件|xlsx文件|*.xlsx";   // "数据文件|*.txt|所有文件|*.*";  // doc文件类似
if (fileDialog.ShowDialog() != DialogResult.OK)
{
    return;
}
string pathFileName = fileDialog.FileName; 

// (3) 读取和写入Excel、并且刷新Excel中的公式
// 1. 创建读取流
FileStream _fsread = new FileStream(fileName, FileMode.Open, FileAccess.Read); // 修改数据显示读取
IWorkbook iWBk = new XSSFWorkbook(_fsread); // 操作 Excel2007
// 2. 创建文件流
FileStream _fsWrite = new FileStream(fileName, FileMode.Create, FileAccess.Write); // 再写入
try
{
    // 3. 通过Sheet名 获取对应的ISeet--其中 ReadWorkbook 为读取Excel文档时获取
    var iWBkSheetIndex = iWBk.GetSheet("Sheet1");
    for (int i = 0; i < 7; i++)
    {
        iWBkSheetIndex.GetRow(i).GetCell(4).SetCellValue("内容");
    }
    // 4. 重新刷新Excel中的公式
    iWBk.GetCreationHelper().CreateFormulaEvaluator().EvaluateAll();
    // 5. 对 Workbook 的修改写入文件流,对文件进行相应操作
    iWBk.Write(_fsWrite);
}
catch (Exception ex)
{
    throw ex;
}
finally
{     // 6. 关闭文件流
    _fsread.Close();
    _fsWrite.Close();
}

// (4) 读取和写入文本文档

// 窗体数据 写入Txt文档
private void SaveFormContent()
{
    string fileName = "Test.txt";
    string formName = "[TestForm]";
    List<string> formData = new List<string>() { formName, m_formData };
    if (!File.Exists(fileName))
    {
        File.Create(fileName); // 路径为程序输入目录下 // \\bin\\Debug\\Test.txt
    }

    File.WriteAllLines(fileName, formData);
}

// 读取Txt文档 填充窗体数据
private void LoadFormContent()
{
    string fileName = Path.Combine("Test.txt");
    if (File.Exists(fileName))
    {
        List<string> contentLine = File.ReadAllLines(fileName).ToList();
        int contentIndex = 0; // 需要获取这一行内容的索引值
        for (int i = 0; i < contentLine.Count; i++)
        {
            if (contentLine[i].Equals("[TestForm]"))
            {
                contentIndex = i + 1;
                break;
            }
        }

        m_formData = contentLine[contentIndex];
    }
}

// (5) NPOI读取和写入Word
https://www.cnblogs.com/mqxs/p/14333564.html

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
你可以使用C#中的SerialPort类来连接扫描枪,并使用Excel Interop或者一些第三方库来将读取到的内容写入Excel文档中。 以下是一个简单的示例代码,仅供参考: ```csharp using System; using System.IO.Ports; using Excel = Microsoft.Office.Interop.Excel; namespace ScanGunExcel { class Program { static SerialPort _serialPort; static Excel.Application _excelApp; static Excel.Workbook _workbook; static Excel.Worksheet _worksheet; static int _row = 1; static void Main(string[] args) { // 初始化串口连接 _serialPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One); _serialPort.DataReceived += SerialPort_DataReceived; _serialPort.Open(); // 初始化Excel文档 _excelApp = new Excel.Application(); _workbook = _excelApp.Workbooks.Add(); _worksheet = _workbook.Worksheets[1]; _worksheet.Cells[1, 1] = "ScanGun Content"; Console.WriteLine("Press any key to stop."); Console.ReadKey(); // 关闭串口连接和Excel文档 _serialPort.Close(); _workbook.SaveAs("ScanGun.xlsx"); _excelApp.Quit(); } private static void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { string content = _serialPort.ReadLine().Trim(); // 写入Excel文档 _worksheet.Cells[_row, 1] = content; _row++; } } } ``` 在这个示例中,我们使用SerialPort类来连接扫描枪。每当扫描枪读取到内容时,SerialPort_DataReceived事件会被触发,我们将读取到的内容写入Excel文档中。最后,我们通过调用Excel Interop的API来保存Excel文档,并关闭Excel应用程序。 需要注意的是,使用Excel Interop可能需要你安装Microsoft Office软件,并且在使用完Excel对象后需要释放资源,否则可能会导致内存泄漏。另外,如果你不想使用Excel Interop,你也可以考虑使用一些第三方库,例如EPPlus或者NPOI来操作Excel文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

马鹤道士

您的认可是我最快乐的事情,谢谢

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值