C#實(shí)現(xiàn)設(shè)置Excel表格中文本對(duì)齊方式和格式
在 Excel 中,對(duì)齊、換行和旋轉(zhuǎn)是用于設(shè)置單元格內(nèi)容顯示方式的功能。合理的設(shè)置這些文本選項(xiàng)可以幫助用戶更好地組織和展示 Excel 表格中的數(shù)據(jù),使表格更加清晰、易讀,提高數(shù)據(jù)的可視化效果。本文將介紹如何在.NET 程序中通過C# 設(shè)置Excel單元格中文本的對(duì)齊方式、方向以及換行。
安裝所需.NET庫(kù)
本文需要用到一個(gè)名為 Free Spire.XLS for .NET 的免費(fèi)國(guó)產(chǎn)庫(kù)。該庫(kù)支持多種Excel文檔操作功能,包括生成、讀取、編輯、打印、轉(zhuǎn)換等。
該庫(kù)可以直接通過Visual Studio > NuGet程序包管理器中搜索 “FreeSpire.XLS” 來安裝。
C# 設(shè)置Excel中文本的對(duì)齊方式、方向以及換行
免費(fèi)Spire.XLS庫(kù)的 CellStyle 類提供了多種屬性來設(shè)置單元樣式包括其中的文本對(duì)齊。旋轉(zhuǎn)等。具體步驟參考:
- 創(chuàng)建一個(gè)Excel工作簿并獲取其中指定工作表。
- 通過 Worksheet.Range[] 屬性獲取指定單元格或單元格范圍
- 通過 CellRange.Style 屬性獲取單元格樣式。
- 通過 CellStyle.HorizontalAlignment 屬性設(shè)置單元格中文字的水平對(duì)齊方式,包括左對(duì)齊(HorizontalAlignType.Left)、水平居中對(duì)齊(HorizontalAlignType.Center)、和右對(duì)齊(HorizontalAlignType.Right)。
- 通過 CellStyle.VerticalAlignment 屬性設(shè)置單元格中文字的垂直對(duì)齊方式,包括靠上對(duì)齊(VerticalAlignType.Top)、垂直居中對(duì)齊(VerticalAlignType.Center)、和靠下對(duì)齊(VerticalAlignType.Bottom)。
- 通過 CellStyle.Rotation 屬性旋轉(zhuǎn)單元格中的文字旋轉(zhuǎn)至指定角度。
- 通過 CellStyle.WrapText 屬性設(shè)置文本自動(dòng)換行,手動(dòng)換行可以添加換行符\n 。
- 保存生成文件。
C#代碼:
using Spire.Xls; namespace SetExcelColumnWidth { class Program { static void Main(string[] args) { // 創(chuàng)建工作簿 Workbook wookbook = new Workbook(); // 獲取第一張工作表 Worksheet sheet = wookbook.Worksheets[0]; // 添加說明文字 sheet.Range["B1"].Text = "文字對(duì)齊方式"; sheet.Range["D1"].Text = "文字方向"; sheet.Range["F1"].Text = "文字換行"; sheet.Range["B1:F1"].Style.Font.IsBold = true; sheet.Range["B1:F1"].Style.KnownColor = ExcelColors.LightGreen; // 左對(duì)齊 sheet.Range["B3"].Text = "左對(duì)齊"; sheet.Range["B3"].Style.HorizontalAlignment = HorizontalAlignType.Left; // 水平居中 sheet.Range["B4"].Text = "水平居中"; sheet.Range["B4"].Style.HorizontalAlignment = HorizontalAlignType.Center; // 右對(duì)齊 sheet.Range["B5"].Text = "右對(duì)齊"; sheet.Range["B5"].Style.HorizontalAlignment = HorizontalAlignType.Right; // 居上 sheet.Range["B7"].Text = "靠上"; sheet.Range["B7"].Style.VerticalAlignment = VerticalAlignType.Top; // 垂直居中 sheet.Range["B8"].Text = "垂直居中"; sheet.Range["B8"].Style.VerticalAlignment = VerticalAlignType.Center; // 居下 sheet.Range["B9"].Text = "靠下"; sheet.Range["B9"].Style.VerticalAlignment = VerticalAlignType.Bottom; // 分散對(duì)齊并居中 sheet.Range["B10"].Text = "水平分散對(duì)齊+垂直居中"; sheet.Range["B10"].Style.HorizontalAlignment = HorizontalAlignType.Distributed; sheet.Range["B10"].Style.VerticalAlignment = VerticalAlignType.Center; // 逆時(shí)針旋轉(zhuǎn)45° sheet.Range["D7"].Text = "旋轉(zhuǎn)45°"; sheet.Range["D7"].Style.Rotation = 45; // 逆時(shí)針旋轉(zhuǎn)90° sheet.Range["D8"].Text = "旋轉(zhuǎn)90°"; sheet.Range["D8"].Style.Rotation = 90; // 順時(shí)針旋轉(zhuǎn)45° sheet.Range["D9"].Text = "旋轉(zhuǎn)-45°"; sheet.Range["D9"].Style.Rotation = -45; // 順時(shí)針旋轉(zhuǎn)90° sheet.Range["D10"].Text = "旋轉(zhuǎn)-90°"; sheet.Range["D10"].Style.Rotation = -90; // 添加‘\n'進(jìn)行文字換行 sheet.Range["F8"].Text = "這是\n手動(dòng)\n換行"; // 自動(dòng)換行 sheet.Range["F9"].Text = "這一段話設(shè)置了自動(dòng)換行"; sheet.Range["F9"].Style.WrapText = true; // 設(shè)置行高列寬 sheet.Columns[1].ColumnWidth = 15; sheet.Columns[3].ColumnWidth = 15; sheet.Columns[5].ColumnWidth = 15; sheet.Range["B3:B5"].RowHeight = 15; sheet.Range["B7:B10"].RowHeight = 50; // 保存文檔 wookbook.SaveToFile("Excel文本對(duì)齊.xlsx", FileFormat.Version2013); } } }
生成文檔:
知識(shí)擴(kuò)展
C# 對(duì)Excel 單元格格式, 及行高、 列寬、 單元格邊框線、 凍結(jié)設(shè)置
1.對(duì)行高,列寬、單元格邊框等的設(shè)置
這篇簡(jiǎn)短的文字對(duì)單元格的操作總結(jié)的比較全面,特此轉(zhuǎn)載過來。
private _Workbook _workBook = null; private Worksheet _workSheet = null; private Excel.Application _excelApplicatin = null; _excelApplicatin = new Excel.Application(); _excelApplicatin.Visible = true; _excelApplicatin.DisplayAlerts = true; _workBook = _excelApplicatin.Workbooks.Add(XlSheetType.xlWorksheet); _workSheet = (Worksheet)_workBook.ActiveSheet; _workSheet.Name = "workSheetName"; //打開已存在的Excel string strExcelPathName = AppDomain.CurrentDomain.BaseDirectory + "excelSheetName.xls"; Excel.Workbook workBook = application.Workbooks.Open(strExcelPathName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); //讀取已打開的Excel Excel.Worksheet workSheet1 = (Excel.Worksheet)workBook.Sheets["SheetName1"]; Excel.Worksheet workSheet2 = (Excel.Worksheet)workBook.Sheets["SheetName2"]; //添加一個(gè)workSheet Worksheet workSheet = (Worksheet)workBook.Worksheets.Add(System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing); //RowHeight "1:1"表示第一行, "1:2"表示,第一行和第二行 ((Excel.Range)_workSheet.Rows["1:1", System.Type.Missing]).RowHeight = 100; //ColumnWidth "A:B"表示第一列和第二列, "A:A"表示第一列 ((Excel.Range)_workSheet.Columns["A:B", System.Type.Missing]).ColumnWidth = 10; // EXCEL操作(需要凍結(jié)的字段 按住ALT+W 再按F) Excel.Range excelRange = _workSheet .get_Range(_workSheet .Cells[10, 5], _workSheet .Cells[10, 5]); excelRange.Select(); excelApplication.ActiveWindow.FreezePanes = true; //Borders.LineStyle 單元格邊框線 Excel.Range excelRange = _workSheet.get_Range(_workSheet.Cells[2, 2], _workSheet.Cells[4, 6]); //單元格邊框線類型(線型,虛線型) excelRange.Borders.LineStyle = 1; excelRange.Borders.get_Item(XlBordersIndex.xlEdgeTop).LineStyle = Excel.XlLineStyle.xlContinuous; //指定單元格下邊框線粗細(xì),和色彩 excelRange.Borders.get_Item(XlBordersIndex.xlEdgeBottom).Weight = Excel.XlBorderWeight.xlMedium; excelRange.Borders.get_Item(XlBordersIndex.xlEdgeBottom).ColorIndex =3; //設(shè)置字體大小 excelRange.Font.Size = 15; //設(shè)置字體是否有下劃線 excelRange.Font.Underline = true; //設(shè)置字體在單元格內(nèi)的對(duì)其方式 excelRange.HorizontalAlignment = XlHAlign.xlHAlignCenter; //設(shè)置單元格的寬度 excelRange.ColumnWidth = 15; //設(shè)置單元格的背景色 excelRange.Cells.Interior.Color = System.Drawing.Color.FromArgb(255, 204, 153).ToArgb(); // 給單元格加邊框 excelRange.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThick, XlColorIndex.xlColorIndexAutomatic, System.Drawing.Color.Black.ToArgb()); //自動(dòng)調(diào)整列寬 excelRange.EntireColumn.AutoFit(); // 文本水平居中方式 excelRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; //文本自動(dòng)換行 excelRange.WrapText = true; //填充顏色為淡紫色 excelRange.Interior.ColorIndex = 39; //合并單元格 excelRange.Merge(excelRange.MergeCells); _workSheet.get_Range("A15", "B15").Merge(_workSheet.get_Range("A15", "B15").MergeCells); /// <summary> /// 常用顏色定義,對(duì)就Excel中顏色名 /// </summary> public enum ColorIndex { 無色 = -4142, 自動(dòng) = -4105, 黑色 = 1, 褐色 = 53, 橄欖 = 52, 深綠 = 51, 深青 = 49, 深藍(lán) = 11, 靛藍(lán) = 55, 灰色80 = 56, 深紅 = 9, 橙色 = 46, 深黃 = 12, 綠色 = 10, 青色 = 14, 藍(lán)色 = 5, 藍(lán)灰 = 47, 灰色50 = 16, 紅色 = 3, 淺橙色 = 45, 酸橙色 = 43, 海綠 = 50, 水綠色 = 42, 淺藍(lán) = 41, 紫羅蘭 = 13, 灰色40 = 48, 粉紅 = 7, 金色 = 44, 黃色 = 6, 鮮綠 = 4, 青綠 = 8, 天藍(lán) = 33, 梅紅 = 54, 灰色25 = 15, 玫瑰紅 = 38, 茶色 = 40, 淺黃 = 36, 淺綠 = 35, 淺青綠 = 34, 淡藍(lán) = 37, 淡紫 = 39, 白色 = 2 }
Code segment2
range.NumberFormatLocal = "@"; //設(shè)置單元格格式為文本 range = (Range)worksheet.get_Range("A1", "E1"); //獲取Excel多個(gè)單元格區(qū)域:本例做為Excel表頭 range.Merge(0); //單元格合并動(dòng)作 worksheet.Cells[1, 1] = "Excel單元格賦值"; //Excel單元格賦值 range.Font.Size = 15; //設(shè)置字體大小 range.Font.Underline=true; //設(shè)置字體是否有下劃線 range.Font.Name="黑體"; 設(shè)置字體的種類 range.HorizontalAlignment=XlHAlign.xlHAlignCenter; //設(shè)置字體在單元格內(nèi)的對(duì)其方式 range.ColumnWidth=15; //設(shè)置單元格的寬度 range.Cells.Interior.Color=System.Drawing.Color.FromArgb(255,204,153).ToArgb(); //設(shè)置單元格的背景色 range.Borders.LineStyle=1; //設(shè)置單元格邊框的粗細(xì) range.BorderAround(XlLineStyle.xlContinuous,XlBorderWeight.xlThick,XlColorIndex.xlColorIndexAutomatic,System.Drawing.Color.Black.ToArgb()); //給單元格加邊框 range.Borders.get_Item(Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeTop).LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlLineStyleNone; //設(shè)置單元格上邊框?yàn)闊o邊框 range.EntireColumn.AutoFit(); //自動(dòng)調(diào)整列寬 Range.HorizontalAlignment= xlCenter; // 文本水平居中方式 Range.VerticalAlignment= xlCenter //文本垂直居中方式 Range.WrapText=true; //文本自動(dòng)換行 Range.Interior.ColorIndex=39; //填充顏色為淡紫色 Range.Font.Color=clBlue; //字體顏色 xlsApp.DisplayAlerts=false; //保存Excel的時(shí)候,不彈出是否保存的窗口直接進(jìn)行保存
Excel Interior.ColorIndex色彩列表
對(duì)用的Interior.ColorIndex色彩列表。
在C# 對(duì)Excel編程中的使用:
for (int i = 5; i < countRow + 1; i++) { string strKB = null; Microsoft.Office.Interop.Excel.Range kbrng = (Microsoft.Office.Interop.Excel.Range)sheSource.Cells[i, 1]; if (kbrng.Value2 != null) strKB = kbrng.Value2.ToString(); if (strTotal.Contains(strKB)) kbrng.Interior.ColorIndex = 3; }
2.常見的Excel單元格格式設(shè)置內(nèi)容
數(shù)字(Range.NumberFormatlocal 屬性)
常規(guī):
Range.NumberFormatlocal = "G/通用格式"
數(shù)值:
Range.NumberFormatlocal = "0.000_" --保留小 數(shù)位數(shù)為3 (此處“_”表示:留下一個(gè)與下一個(gè)字符同等寬度的空格)
Range.NumberFormatlocal = "0" --不要小數(shù)
Range.NumberFormatlo cal = "#,##0.000" --保留小數(shù)位數(shù)為3,并使用千位分隔符
貨幣:
Range.NumberFormatlocal = "$#,##0.000"
百分比:
Range.NumberFormatlocal = "0.000%"
分?jǐn)?shù):
Range.NumberFormatlocal = "# ?/?"
科學(xué)計(jì)數(shù):
Range.NumberFormatlocal = "0.00E+00"
文本
Range.NumberFormatlocal = "@"
特殊:
- Range.NumberFormatlocal = "000000"---郵政編碼
- Range.NumberFormatlocal = "[DBNum1]G/通用格式"---中文小寫數(shù)字
- Range.NumberFormatlocal = "[DBNum2]G/通用格式"---中文大寫數(shù)字
- Range.NumberFormatlocal = "[DBNum2][$RMB]G/通用格式"---人民幣大寫
對(duì)齊
- 水平對(duì)齊:Range.HorizontalAlignment = etHAlignCenter ---居中
- 垂 直對(duì)齊:Range.VerticalAlignment = etVAlignCenter---居中
- 是否自動(dòng)換行:Range.WrapText = True
- 是否縮小字體填充:Range.ShrinkToFit = True
- 是否合并單元格:Range.MergeCells = False
- 文字豎排:Range.Orientation = etVertical
- 文字傾斜度數(shù):Range.Orientation = 45 -----傾斜45度
字體(Font對(duì)象)
- 字體名稱:Font.Name = "華文行楷"
- 字形: Font.FontStyle = "常規(guī)"
- 字號(hào):Font.Size = "10"
- 下劃線:Font.Strikethrough = True; Font.Underline = etUnderlineStyleDouble ---雙下劃線
- 上標(biāo):Font.Superscript = True
- 下 標(biāo):Font.SubScript = True
- 刪除線:Font.OutlineFont = True
邊框(Borders對(duì)象)
- Borders.Item(etEdgeTop):上邊框
- Borders.Item(etEdgeLeft):左邊框
- Borders.Item (etEdgeRight):右邊框
- Borders.Item(etEdgeBottom):下邊框
- Borders.Item(etDiagonalDown) :左上--右下邊框
- Borders.Item(etDiagonalUp):左下--右上邊框
- Border.LineStyle = etContinuous 線條樣式
到此這篇關(guān)于C#實(shí)現(xiàn)設(shè)置Excel表格中文本對(duì)齊方式和格式的文章就介紹到這了,更多相關(guān)C#設(shè)置Excel表格文本格式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
c#實(shí)現(xiàn)萬年歷示例分享 萬年歷農(nóng)歷查詢
這篇文章主要介紹了c#實(shí)現(xiàn)萬年歷的方法,可以顯示農(nóng)歷、節(jié)氣、節(jié)日、星座、星宿、屬相、生肖、閏年月、時(shí)辰,大家參考使用吧2014-01-01詳解C#設(shè)置Excel數(shù)據(jù)自適應(yīng)行高、列寬的2種情況
這篇文章主要介紹了C#設(shè)置Excel數(shù)據(jù)自適應(yīng)行高、列寬的2種情況,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04C#使用selenium實(shí)現(xiàn)操作瀏覽器并且截圖
這篇文章主要為大家詳細(xì)介紹了C#如何使用selenium組件實(shí)現(xiàn)操作瀏覽器并且截圖,文中的示例代碼簡(jiǎn)潔易懂,有需要的小伙伴可以參考一下2024-01-01C#中GraphicsPath的Flatten方法用法實(shí)例
這篇文章主要介紹了C#中GraphicsPath的Flatten方法,實(shí)例分析了Flatten方法的相關(guān)使用技巧,需要的朋友可以參考下2015-06-06c# 調(diào)用.bat文件的實(shí)現(xiàn)代碼
c# 調(diào)用.bat文件主要利用了using System.Diagnostics;命名空間,大家可以參考下。2009-06-06C#中科學(xué)繪圖庫(kù)ScottPlot的使用詳解
ScottPlot是基于.Net的一款開源免費(fèi)的交互式可視化庫(kù),支持Winform和WPF等UI框架,本文給大家介紹了C#中科學(xué)繪圖庫(kù)ScottPlot的使用方法,文中示例在WPF環(huán)境中運(yùn)行,需要的朋友可以參考下2023-12-12