c# - 如何使用 C# .NET 为 excel 添加自动调整列数据
问题描述
private void copyAlltoClipboard()
{
sdataGridView.SelectAll();
DataObject dataObj = sdataGridView.GetClipboardContent();
if (dataObj != null)
Clipboard.SetDataObject(dataObj);
}
private void button1_Click(object sender, EventArgs e)
{
copyAlltoClipboard();
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 Microsoft.Office.Interop.Excel.Application();
xlexcel.Visible = true;
xlWorkBook = xlexcel.Workbooks.Add(misValue);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
CR.Select();
xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
}
我正在使用这段代码将我的datagridview数据导出到excel,但我想为包括标题的列文本添加自动调整或合并列数据。我不知道该怎么做。非常感谢任何帮助。
解决方案
要调整列宽,您可以执行以下操作:
Excel.Range xlEntireColumn = null;
Excel.Range xlRange = null;
while (reader.Read()) {
for (int i=0;i<numcols;i++) {
xlsheet.ActiveSheet.Cells[row,i+1] = reader.GetValue(i).ToString();
xlRange = xlSheet.ActiveSheet.Cells[row, i+1];
xlEntireColumn = xlRange.EntireColumn;
xlEntireColumn.AutoFit();
}
也检查一下.. https://www.dotnetfunda.com/codes/show/1071/export-to-excel-with-grid-color-in-winforms-using-csharp
推荐阅读
- jquery - 在等待 getJSON 时显示加载 gif
- java - 使用类型参数覆盖泛型方法时出现编译错误
- javascript - 使 3DSierpinskiTriangle 旋转
- wordpress - 为什么我的 Google 地图插件 KML 功能只能在某些地区使用?它在纽约和法国有效,但在德克萨斯州无效
- routing - 访问 L2TP 服务器后面的 LAN 子网
- rabbitmq - 如何动态创建消费者 Rabbitmq?
- javascript - ReactJS 获得一个 Enter 键来执行与单击按钮相同的操作
- html - 在 R Shiny 中使用 a() 时的尾随空格
- azure - 更新 Azure 表存储记录时如何避免竞争条件
- java - 显示数组的重复项,例如“数字 x 重复 x 次