我们知道C1XLBook可以用来导入Excel文件或是创建一个新的。也可以添加表单、样式,图片,列头和列尾等。
当单元格设置了样式或是有其他的操作导致了单元格的文字长度超过单元格宽度,比如列宽。C1XLBook并没有内置的方法或是属性,可以自动调整列宽。
本文就来介绍如何用代码来实现这个功能。
首先需要将C1XLBook组件添加到应用程序窗体。
然后创建两列的表单。
接着创建样式和分配大的字体给一种样式使得单元格文字超过单元格宽度。
代码参考:
c1XLBook1.Clear(); /*Create test Styles*/ XLStyle s1 = new XLStyle(c1XLBook1); XLStyle s2 = new XLStyle(c1XLBook1); XLStyle s3 = new XLStyle(c1XLBook1); s1.Format = "#,##0.00000"; s2.Format = "#,##0.00000"; /*Assign a large enough Font*/ s2.Font = new Font("Courier New", 14); s3.Format = "dd-MMM-yy"; C1.C1Excel.XLSheet sheet = c1XLBook1.Sheets[0]; Random r = new Random(); for (int i = 0; i < 100; i++) { sheet[ i, 0 ].Value = r.NextDouble() * 100000; /*Assign the style with enlarged Font to every cell in 13th Row of first Column*/ sheet[ i, 0 ].Style = (i % 13 == 0) ? s2 : s1; } for (int i = 0; i < 100; i++) { sheet[ i, 1 ].Value = new DateTime(2005, r.Next(1, 12), r.Next(1, 28)); sheet[ i, 1 ].Style = s3; } string tempdir = Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf("\\") + 1); /*Save sheet with default column width*/ c1XLBook1.Save(tempdir + @"defaultWidth.xls");
然而,表单是默认的宽度-没有改变尺寸。
我们使用如下代码来完成这个需求。
private void AutoSizeColumns(XLSheet sheet) { /*No Graphics instance available because there's no Paint event*/ /*Create a Graphics object using a handle to current window instead*/ using (Graphics g = Graphics.FromHwnd(IntPtr.Zero)) { /*Traverse rows and columns*/ for (int c = 0; c < sheet.Columns.Count; c++) { int colWidth = -1; for (int r = 0; r < sheet.Rows.Count; r++) { /*Get cell value*/ object value = sheet[r, c].Value; if (value != null) { string text = value.ToString(); /*Get Style for this cell*/ C1.C1Excel.XLStyle s = sheet[r, c].Style; if (s != null && s.Format.Length > 0 && value is IFormattable) { string fmt = XLStyle.FormatXLToDotNet(s.Format); /*get formatted text*/ text = ((IFormattable)value).ToString(fmt, CultureInfo.CurrentCulture); } Font font = this.c1XLBook1.DefaultFont; if (s != null && s.Font != null) { font = s.Font; } /*Get size of drawn string according to its Font*/ Size sz = Size.Ceiling(g.MeasureString(text + "XX", font)); if (sz.Width > colWidth) colWidth = sz.Width; } } /*Set columns width*/ if (colWidth > -1) sheet.Columns[c].Width = C1XLBook.PixelsToTwips(colWidth); } } }
现在,简单的调用方法,就可以实现调整列宽的需求。
最后,如果需要导出到Excel,就可以将自动调整列宽的表单导出到Excel。
代码参考:
/*Resize columns*/ AutoSizeColumns(sheet); /*Save sheet with resized columns*/ c1XLBook1.Save(tempdir + @"autoSized.xls"); System.Diagnostics.Process.Start(tempdir + @"autoSized.xls");
效果如图:
当然,这个并不适合合并或者折行的单元格。
本文的Demo请下载:
更多内容:
C1Excel控件简介:/developer/componentone-winform/controls/excel
C1Excel的下载地址:/download/?pid=3
如需更多帮助,可以到葡萄城开发者社区寻找更多资源以及帮助,地址:http://gcdn.grapecity.com.cn/