C#-Write Contents in Excel 2007
I have used MS Office 2003 for several years, even though it published new versions and improved performance. Firstly, I am very familiar with Office 2003. Once, I used 2007 but it took me a little long time to find the function I wanted to use. Secondly, I needed to pay money on getting new version.
However, sometimes, we need the new versions documents for meeting special requirements. Actually, MS Office provides us a function to realize conversion between Office 2003 and newer versions. For example, we can convert an Excel 2007 file (.xlsx) to Excel 2003 file (.xls), vice versa.
Now, I want to introduce a method to write content in Excel 2007 by using C#. This method is based on a component: Spire.XLS, which specializes in working on Excel for Silverlight and .NET. This component supports Excel versions 2003, 2007 and 2010.
Therefore, at first, we need to add its DLL file as reference. And then use the following code.
using System;
using Spire.Xls;
using System.Drawing;
namespace Excel2007
{
class Program
{
static void Main(string[] args)
{
Workbook workbook = new Workbook();
workbook.CreateEmptySheets(1);
Worksheet sheet = workbook.Worksheets[0];
workbook.Version = ExcelVersion.Version2007;
int maxColor = Enum.GetValues(typeof(ExcelColors)).Length;
Random random = new Random((int)System.DateTime.Now.Ticks);
for (int i = 2; i < 40; i++)
{
ExcelColors backKnownColor = (ExcelColors)(random.Next(1, maxColor / 2));
sheet.Range["A1"].Text = "Color Name";
sheet.Range["B1"].Text = "Red";
sheet.Range["C1"].Text = "Green";
sheet.Range["D1"].Text = "Blue";
sheet.Range["E1:K1"].Merge();
sheet.Range["E1:K1"].Text = "Gradient";
sheet.Range["A1:K1"].Style.Font.IsBold = true;
sheet.Range["A1:K1"].Style.Font.Size = 11;
string colorName = backKnownColor.ToString();
sheet.Range[string.Format("A{0}", i)].Text = colorName;
sheet.Range[string.Format("B{0}", i)].Text = workbook.GetPaletteColor(backKnownColor).R.ToString();
sheet.Range[string.Format("C{0}", i)].Text = workbook.GetPaletteColor(backKnownColor).G.ToString();
sheet.Range[string.Format("D{0}", i)].Text = workbook.GetPaletteColor(backKnownColor).B.ToString();
sheet.Range[string.Format("E{0}:K{0}", i)].Merge();
sheet.Range[string.Format("E{0}:K{0}", i)].Text = colorName;
sheet.Range[string.Format("E{0}:K{0}", i)].Style.Interior.FillPattern = ExcelPatternType.Gradient;
sheet.Range[string.Format("E{0}:K{0}", i)].Style.Interior.Gradient.BackKnownColor = backKnownColor;
sheet.Range[string.Format("E{0}:K{0}", i)].Style.Interior.Gradient.ForeKnownColor = ExcelColors.White;
sheet.Range[string.Format("E{0}:K{0}", i)].Style.Interior.Gradient.GradientStyle = GradientStyleType.Vertical;
sheet.Range[string.Format("E{0}:K{0}", i)].Style.Interior.Gradient.GradientVariant = GradientVariantsType.ShadingVariants1;
}
sheet.AutoFitColumn(1);
workbook.SaveToFile("Excel2007.xlsx");
System.Diagnostics.Process.Start(workbook.FileName);
}
}
}
|