如何在excel c# win表单中编写粗体文本

本文关键字:文本 表单 excel win | 更新日期: 2023-09-27 18:08:56

我使用这个代码,并希望在标题上加粗,请帮助我。

想要创建设计的excel表,出口后看起来很好。在其他方式下修改但是想用这种方式修改excel表格。

StreamWriter wr = new StreamWriter(@"D:''test.xls");

foreach (string sHeader in Header)
{
      wr.Write(sHeader);
      wr.WriteLine();
}
wr.Write("");
wr.WriteLine();
for (int i = 0; i < Dt.Columns.Count; i++)
{
      wr.Write(Dt.Columns[i].ToString().ToUpper() + "'t");
}
wr.WriteLine();
//write rows to excel file
for (int i = 0; i < (Dt.Rows.Count); i++)
{
     for (int j = 0; j < Dt.Columns.Count; j++)
     {
            if (Dt.Rows[i][j] != null)
            {
                wr.Write(Convert.ToString(Dt.Rows[i][j]) + "'t");
            }
            else
            {
                wr.Write("'t");
            }
      }
      //go to next line
      wr.WriteLine();
}
//close file
wr.Close();

如何在excel c# win表单中编写粗体文本

添加此引用并尝试此操作"使用Microsoft.Office.Interop.Excel.ApplicationClass"

 try
    {
        SaveFileDialog sfd = new SaveFileDialog();
        sfd.FileName = "Total Expiry Inventories Data ";
        sfd.DefaultExt = "xls";
        sfd.Filter = "xlsx files(*.xlsx)|*.xlsx";
        if (sfd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
        {
            return;
        }
        Excel.Application ExcelApp = new Excel.Application();
        Excel.Workbook workbook = ExcelApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
        Excel.Worksheet worksheet1 = (Excel.Worksheet)workbook.Worksheets[1];
        worksheet1.Name = "Expiry Data";
        for (int i = 1; i < GrdViewData.Columns.Count + 1; i++)
        {
            worksheet1.Cells[1, i] = GrdViewData.Columns[i - 1].HeaderText;
            worksheet1.Cells[1, i].Font.Bold = true;

        }
        for (int i = 0; i < GrdViewData.Rows.Count; i++)
        {
            for (int j = 0; j < GrdViewData.Columns.Count; j++)
            {
                worksheet1.Cells[i + 2, j + 1] = GrdViewData.Rows[i].Cells[j].Value.ToString();
            }
        }
        worksheet1.Rows.Font.Size = 12;
        //  Excel.Range range_Consolidated = worksheet1.Rows.get_Range("a1", "d1");
        // range_Consolidated.Font.Bold = true;
        // range_Consolidated.Font.Italic = true;
        string ExcelFileName = sfd.FileName;
        workbook.SaveAs(ExcelFileName);
        workbook.Close(false, ExcelFileName, Missing.Value);
        ExcelApp.Quit();
        ExcelApp = null;
        GC.Collect();
        GC.WaitForPendingFinalizers();
        MessageBox.Show("File Saved! you can open it from'n  '" + sfd.FileName + "'", "EXPORT", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
    }