private void ExportExcel_Click(object sender, EventArgs e)
{
Workbook workBook = new
Workbook(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop) + "\\" + "1.xlsx");
workBook.Worksheets.Clear(); //清除默认sheet
string sheetNames = "Test";
CreateSheetByName(workBook, new string[] { sheetNames });
MergeCells(workBook, sheetNames, new int[] { 2, 3, 1, 3 }, 0, new string[] { "合并两列", "合并三列", "合并一列", "合并三列" });
MergeCells(workBook, sheetNames, new int[] { 2, 1, 1, 1, 1, 1, 1, 1 }, 1, new string[] { "合并两列", "合并一列", "合并一列", "合并一列", "合并一列", "合并一列", "合并一列", "合并一列" });
//SetCellsStyle(workBook,sheetNames);
List<string[]> values = new List<string[]>()
{
new string[]{"1","2","3","4","5","6","7","8","9"},
new string[]{"1","2","3","4","5","6","7","8","9"},
new string[]{"1","2","3","4","5","6","7","8","9"},
new string[]{"1","2","3","4","5","6","7","8","9"}
};
ExportDataToExcel(workBook,sheetNames, values, 2);
Save(workBook);
}
//private void SetCellsStyle(Workbook workBook, string sheetNames)
//{
// Style style = workBook.CreateStyle();
// style.HorizontalAlignment = TextAlignmentType.Center;
// Cells cells = workBook.Worksheets[sheetNames].Cells;
// cells[0, 0].SetStyle(style);
// cells[0, 2].SetStyle(style);
// cells[0, 6].SetStyle(style);
//
}
private void Save(Workbook workBook)
{
SaveFileDialog SFD = new SaveFileDialog();
SFD.Filter = "EXCEL文件(*.xls)|*.xls|EXCEL文件(*.xlsx)|*.xlsx";
SFD.FileName = "新建 Microsoft Excel 工作表";
if (SFD.ShowDialog() == DialogResult.OK)
{
workBook.Save(SFD.FileName);
}
}
private void ExportDataToExcel(Workbook wb , string sheetName, List<string[]> values, int firstRow)
{
Cells cells = wb.Worksheets[sheetName].Cells;
for (int i = 0; i < values.Count ; i++)
{
string[] tempValue = values[i];
for (int j = 0; j < tempValue.Length ; j++)
{
cells[i + firstRow, j].PutValue(tempValue[j]);
}
}
}
private void MergeCells(Workbook wb ,string sheetName, int[] numbers, int firstRow, string[] values)
{
Cells cells = wb.Worksheets[sheetName].Cells;
int firstColumn = 0; //起始合并工作列
for (int i = 0; i < numbers.Length ; i++)
{
int number = numbers[i]; //合并的列数集合
cells.Merge(firstRow, firstColumn, 1, number); //起始行,起始列,合并的行数,合并的列数
cells[firstRow, firstColumn].PutValue(values[i]);
//设置列头居中
Style style = wb.CreateStyle(); //创建样式
style.HorizontalAlignment = TextAlignmentType.Center;
cells[firstRow, firstColumn].SetStyle(style);
firstColumn += number; //合并完的起始工作列号
}
}
private void CreateSheetByName(Workbook wb ,string[] names)
{
foreach (string sheetName in names)
{
if (wb.Worksheets.GetSheetByCodeName(sheetName) == null)
{
wb.Worksheets.Add(sheetName);
AutoFitterOptions options = new AutoFitterOptions();
options.AutoFitMergedCells = true;
wb.Worksheets[sheetName].AutoFitRows(options);
}
}
}
C# Aspose操作Excel
猜你喜欢
转载自blog.csdn.net/qq_35106907/article/details/84782953
今日推荐
周排行