使用Devexpress控件導出數據到Excel,需滿足:
// 1. 準備標準發票模板文件 (InvoiceTemplate.xlsx)
// 2. 使用Devexpress打開模板
IWorkbook workbook = spreadsheetControl.Document;
workbook.LoadDocument("InvoiceTemplate.xlsx");
// 3. 定位數據填充區域
Worksheet sheet = workbook.Worksheets[0];
CellRange dataStart = sheet.Range["A5"]; // 第5行開始填充數據
// 4. 填充固定表頭信息
sheet.Cells["B1"].Value = "公司名稱: ABC有限公司";
sheet.Cells["B2"].Value = "電話: 010-12345678";
sheet.Cells["B3"].Value = "傳真: 010-87654321";
sheet.Cells["B4"].Value = "郵箱: finance@abc.com";
sheet.Cells["D1"].Value = "日期: " + DateTime.Now.ToString("yyyy-MM-dd");
// 5. 數據導入
var dataTable = GetInvoiceData(); // 獲取DataTable
sheet.Import(dataTable, true, dataStart.Row, dataStart.Column.Index);
// 6. 刪除多余標題行 (原第3行,現因插入表頭下移)
sheet.Rows.Remove(2, 1); // 刪除索引2的1行
// 7. 保存/導出
workbook.SaveDocument("Invoice_Output.xlsx", DocumentFormat.Xlsx);
IWorkbook workbook = spreadsheetControl.Document;
Worksheet sheet = workbook.Worksheets["Sheet1"];
// 構建固定表頭
string[] headers = { "公司名稱", "電話", "傳真", "郵箱", "日期" };
string[] values = { "ABC有限公司", "010-12345678", "010-87654321", "finance@abc.com", DateTime.Now.ToString("yyyy-MM-dd") };
for (int i = 0; i < headers.Length; i++) {
sheet.Cells[i, 0].Value = headers[i];
sheet.Cells[i, 1].Value = values[i];
}
// 設置列標題 (第5行)
string[] columns = { "項目", "數量", "單價", "金額" };
for (int j = 0; j < columns.Length; j++) {
sheet.Cells[5, j].Value = columns[j];
}
// 數據填充從第6行開始
sheet.Import(GetInvoiceData(), true, 6, 0);
| 需求 | Devexpress API | 說明 |
|---|---|---|
| 加載模板 | workbook.LoadDocument() | 支持xlsx/xls/csv |
| 單元格賦值 | sheet.Cells[row, col].Value | 支持各類數據類型 |
| 批量導入 | sheet.Import(DataTable, hasHeader, row, col) | 高性能數據寫入 |
| 刪除行 | sheet.Rows.Remove(startIndex, count) | 索引從0開始 |
| 插入行 | sheet.Rows.Insert(index, count) | 向下移動現有行 |
Devexpress官方文檔:Spreadsheet導出Excel完整教程