使用C#和ADO OLEDB连接字符串创建excel文件。如何使excel中的标题行变为粗体?

时间:2011-08-25 14:40:45

标签: c# oledb

我已将连接字符串设置如下: -

“Provider = Microsoft.ACE.OLEDB.12.0; Data Source =”+ saveFilenameAndLocation +“; Extended Properties ='Excel 12.0 xml; HDR = Yes'”

我已指定第一行是标题,我的Excel电子表格是使用标题行创建的,后跟所有数据行。但是,我想让我的标题行加粗,我该怎么做?任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:3)

您需要使用Office Interop;它不能用ADO完成。

通过右键单击解决方案资源管理器中的“引用”,然后单击“添加引用”,将对项目的引用添加到Microsoft.Office.Interop.Excel。然后选择“Microsoft.Office.Interop.Excel”。

这是一个非常简单的示例,用于打开Excel文档,并在单击用户表单上的按钮时使第一行变为粗体。

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

namespace WindowsFormsApplication1
{


    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            String filename = "C:\\Path\\To\\Excel\\File\\file.xls";

            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            xlApp.Visible = true;
            Workbook xlWkb = xlApp.Workbooks.Open(filename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
                Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            Worksheet xlSh = xlWkb.Sheets[1] as Worksheet;
            Range xlRng = xlSh.UsedRange.get_Range("A1", Type.Missing).EntireRow;
            xlRng.Font.Bold = true;
            xlWkb.Save();
            xlApp.Quit();

            xlRng = null;
            xlSh = null;
            xlWkb = null;
            xlApp = null;
        }
    }
}

答案 1 :(得分:1)

OLEDB仅提供对数据的访问,而不是格式化。

要访问单元格属性等,您需要使用Interop(http://msdn.microsoft.com/en-us/library/ms173186%28v=vs.80%29.aspx)或第三方组件,如Spire.xls(http://www.e-iceblue.com/Introduce/excel-for-net-introduce.html,商业广告)或其他类似选项之一(检查Import and Export Excel - What is the best library?)。

相关问题