1,目的:
通过C#代码对Excel进行操作,完成excel 工作簿(WorkBook)的新建,保存。对单元表(worksheet)内容填充,格式设置等。
2,原理:
调用Microsoft.Office.Interop.Excel,借助COM组件,与Excel进行互操作。
3,注意事项:
- 必须安装Office中的Excel,因本质是调用Excel应用完成任务,若无该Excel应用该系列操作将无法完成!
- 通过Microsoft.Office.Interop.Excel中类创建的对象属于COM对象,使用Microsoft.Office.Interop.Excel.Application.Quit()后其进程并未结束,EXCEL进程依旧存在,需要另行结束其进程。
4,相关单元格属性设置资料:
(来源于:https://www.cnblogs.com/zhangchenliang/archive/2012/02/24/2365956.html)
- 全表自动列宽
mysheet.Cells.Select();
mysheet.Cells.Columns.AutoFit();
- 合并
excelRangeParm.Merge(Missing.Value);
- 粗体设置
excelRangeParm.Font.Bold = true;
- 字体大小设置
excelRangeParm.Font.Size = 12;
- 水平对齐设置
excelRangeParm.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
- 垂直对齐设置
excelRangeParm.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;
- 公式设置
excelRangeParm.FormulaR1C1 = 公式;
- 列宽设置
excelRange.ColumnWidth = 宽度;
- 行高
excelRange.RowHeight = 行高;
- 设置列格式
Excel.Range myrange=mysheet.get_Range(mysheet.Cells[1,1],mysheet.Cells[5,1]);
- 文本格式
myrange.NumberFormatLocal="@";
- 通用格式
style.NumberFormatLocal = "[DBNum2][$-804]G/通用格式";
或
range.NumberFormatLocal = "G/通用格式";
xlsheet.Cells[1,1]="''+txtKey.Text;
- 添加行
((Excel.Range)mysheet.Cells[15,3]).EntireRow.Insert(0);
- 设置第10行为红色
mysheet.get_Range((Excel.Range)mysheet.Cells[10,1], (Excel.Range)mysheet.Cells[10,200]).Select();
mysheet.get_Range((Excel.Range)mysheet.Cells[10,1], (Excel.Range)mysheet.Cells[10,200]).Interior.ColorIndex=3;
- 单元格自动换行
myrange.WrapText = true;
- 单元格行高自动调整
myrange.EntireRow.AutoFit();
- 单元格边框颜色
cellRange.Borders.Color = Excel.XlRgbColor.rgbBlue;
- 单元格线型
cellRange.Borders.LineStyle = Excel.XlLineStyle.xlDash;
- 单元格线型宽度
cellRange.Borders.Weight = Excel.XlBorderWeight.xlThick;
补充:
Excel.Range range = xSheet.Range[xSheet.Cells[1, 1], xSheet.Cells[1, columnNum]];
using Excel = Microsoft.Office.Interop.Excel;
5,代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] wordLines= File.ReadAllLines("../../1.txt",Encoding.Default);
//因为一个作者有多部作品所以进行分组
List<AuthorInfo> list = new List<AuthorInfo>();
foreach (var item in wordLines)
{
string[] infos = item.Split(' ');
if (infos.Length < 2) continue;
list.Add(new AuthorInfo { Author = infos[1], Production = infos[0] });
}
//一个作者可能存在多部作品所以进行分组
var arr = list.GroupBy(info => info.Author);
Excel.Application app = new Excel.Application();
//不显示询问弹窗
app.DisplayAlerts = false;
//创建一个工作簿
Excel.Workbook book= app.Workbooks.Add();
foreach (var g in arr)
{
Excel.Worksheet sheet= book.Worksheets.Add();
sheet.Name = g.Key;
//插入图片
AddImage(sheet, Path.GetFullPath("../../1.png"), 1, 5, 5, 7);
int num = 1;
foreach (var item in g)
{
//给sheet单元格设置值
//sheet.Range[sheet.Cells[1, 1],sheet.Cells[num,1]]必须以此格式设置否则报错
Excel.Range range= sheet.Range[sheet.Cells[num, 1], sheet.Cells[num, 1]] as Excel.Range;
//设置单元格格式
if (num % 2 == 1)
{
range.Font.Color = Color.Green;
range.Font.Bold = true;
range.Font.Size = 16;
//range.Font.Background = Color.SkyBlue;//不能设置
range.Interior.Color = Color.SkyBlue;
}
sheet.Cells[num, 1] = item.Production;
num++;
}
//单元表自动调整
sheet.Select();
sheet.Cells.Columns.AutoFit();
}
string filePath = Path.GetFullPath("../../1.xlsx");
book.SaveAs(filePath);
book.Close();
app.Quit();
//注意,进程并未退出而是一直存在,所以这里必须kill 进程
//获取app对应的进程ID
IntPtr hwd = new IntPtr(app.Hwnd);
int id;
GetWindowThreadProcessId(hwd, out id);
//kill该进程
System.Diagnostics.Process.GetProcessById(id).Kill();
MessageBox.Show("已导出!");
}
/// <summary>
/// 向工作表中插入图片
/// </summary>
/// <param name="sheet">需要插入图片的工作表</param>
/// <param name="imageFilePath">图片的绝对路径</param>
/// <param name="startRowNumber">安放图片的起始行</param>
/// <param name="startColumnNumber">安放图片的起始列</param>
/// <param name="endRowNumber">安放图片的终止行</param>
/// <param name="endColumnNumber">安放图片的终止列</param>
public void AddImage(Excel.Worksheet sheet, string imageFilePath, int startRowNumber, int startColumnNumber, int endRowNumber, int endColumnNumber)
{
Excel.Range range = sheet.Range[sheet.Cells[startRowNumber, startColumnNumber], sheet.Cells[endRowNumber, endColumnNumber]];
range.Select();
range.Borders.LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders.Color = Color.Blue;
range.Merge();
float left = Convert.ToSingle(range.Left);
float top = Convert.ToSingle(range.Top);
float width = Convert.ToSingle(range.Width);
float height = Convert.ToSingle(range.Height);
sheet.Shapes.AddPicture(imageFilePath, Microsoft.Office.Core.MsoTriState.msoFalse,
Microsoft.Office.Core.MsoTriState.msoCTrue, left, top, width, height);
}
[DllImport("User32.dll", CharSet = CharSet.Auto)] //调用API函数,目的获取新增EXCEL进程的进程ID
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
}
class AuthorInfo
{
public string Author { get; set; }
public string Production { get; set; }
}