gpt4 book ai didi

c# - 使用 C# 将文本添加到 Excel 工作表中

转载 作者:太空狗 更新时间:2023-10-29 21:13:44 26 4
gpt4 key购买 nike

我正在尝试使用 C# 将很长的文本添加到 Excel 工作表中。我使用这段代码:

worksheet.Cells[1, 1] = textString;

结果在这里:

我想要的是:

建议?

最佳答案

要获得此效果,您必须将文本复制到剪贴板,然后将其粘贴到相关单元格。看这个例子

注意:将textString设置为您的超长字符串。

代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
//~~> Change Your String here
String textString = "I'm trying to add a pretty long text into the Excel sheet by using sheet. I use this code:" + Environment.NewLine +
"worksheet.Cells[1, 1] = textString;" + Environment.NewLine +
"The result is here:";

Clipboard.SetText(textString);

Microsoft.Office.Interop.Excel.Application xlexcel;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;

object misValue = System.Reflection.Missing.Value;
xlexcel = new Excel.Application();
xlexcel.Visible = true;

//~~> Add a new a workbook
xlWorkBook = xlexcel.Workbooks.Add(misValue);

//~~> Set Sheet 1 as the sheet you want to work with
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

//~~> Set your range
Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[1, 1];

CR.Select();

xlWorkSheet.Paste(CR, false);

// xlWorkBook.Close(true, misValue, misValue);
// xlexcel.Quit();

// releaseObject(xlWorkSheet);
// releaseObject(xlWorkBook);
// releaseObject(xlexcel);
}

//private void releaseObject(object obj)
//{
// try
// {
// System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
// obj = null;
// }
// catch (Exception ex)
// {
// obj = null;
// MessageBox.Show("Unable to release the Object " + ex.ToString());
// }
// finally
// {
// GC.Collect();
// }
//}
}
}

快照

enter image description here

关于c# - 使用 C# 将文本添加到 Excel 工作表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11813758/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com