您的位置:首页 > 运维架构

Using DocumentFormat.OpenXml to generate a new excel file in terms of temp excel file

2013-01-23 18:22 836 查看
public class PortfolioReport
{
string TemplateFileName = "Temp.xlsx";
string NewFileName = @"C:\NewFile.xlsx";

private WorkbookPart WbPart = null;

//Manager function
public PortfolioReport()
{
CopyFile(TemplateFileName, NewFileName);
SpreadsheetDocument document = SpreadsheetDocument.Open(NewFileName, true);

WbPart = document.WorkbookPart;
UpdateValue("Summarizing Report", "A4", "A4.Value", 0, true);
UpdateValue("Synchronization Report", "D4", "D4.Value", 0, true);
RemoveCellValue("Synchronization Report", "E1");
document.Close();
}

//Remove the cell value
private bool RemoveCellValue(string sheetName, string addressName)
{
bool returnValue = false;

Sheet sheet = WbPart.Workbook.Descendants<Sheet>().
Where(s => s.Name == sheetName).FirstOrDefault();
if (sheet != null)
{
Worksheet ws = ((WorksheetPart)(WbPart.GetPartById(sheet.Id))).Worksheet;
Cell cell = InsertCellInWorksheet(ws, addressName);

// If there is a cell value, remove it to force a recalculation
// on this cell.
if (cell.CellValue != null)
{
cell.CellValue.Remove();
}

// Save the worksheet.
//ws.Save();
returnValue = true;
}

return returnValue;
}

//Just copy file
private string CopyFile(string source, string dest)
{
string result = "Copied file";
try
{
// Overwrites existing files
File.Copy(source, dest, true);
}
catch (Exception ex)
{
result = ex.Message;
}
return result;
}

//Update the cell value
public bool UpdateValue(string sheetName, string addressName, string value,
UInt32Value styleIndex, bool isString)
{
// Assume failure.
bool updated = false;

Sheet sheet = WbPart.Workbook.Descendants<Sheet>().Where(
(s) => s.Name == sheetName).FirstOrDefault();

if (sheet != null)
{
Worksheet ws = ((WorksheetPart)(WbPart.GetPartById(sheet.Id))).Worksheet;
Cell cell = InsertCellInWorksheet(ws, addressName);

if (isString)
{
// Either retrieve the index of an existing string,
// or insert the string into the shared string table
// and get the index of the new item.
int stringIndex = InsertSharedStringItem(WbPart, value);

cell.CellValue = new CellValue(stringIndex.ToString());
cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
}
else
{
cell.CellValue = new CellValue(value);
cell.DataType = new EnumValue<CellValues>(CellValues.Number);
}

if (styleIndex > 0)
cell.StyleIndex = styleIndex;

// Save the worksheet.
ws.Save();
updated = true;
}

return updated;
}

// Given the main workbook part, and a text value, insert the text into
// the shared string table. Create the table if necessary. If the value
// already exists, return its index. If it doesn't exist, insert it and
// return its new index.
private int InsertSharedStringItem(WorkbookPart wbPart, string value)
{
int index = 0;
bool found = false;
var stringTablePart = wbPart
.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();

// If the shared string table is missing, something's wrong.
// Just return the index that you found in the cell.
// Otherwise, look up the correct text in the table.
if (stringTablePart == null)
{
// Create it.
stringTablePart = wbPart.AddNewPart<SharedStringTablePart>();
}

var stringTable = stringTablePart.SharedStringTable;
if (stringTable == null)
{
stringTable = new SharedStringTable();
}

// Iterate through all the items in the SharedStringTable.
// If the text already exists, return its index.
foreach (SharedStringItem item in stringTable.Elements<SharedStringItem>())
{
if (item.InnerText == value)
{
found = true;
break;
}
index += 1;
}

if (!found)
{
stringTable.AppendChild(new SharedStringItem(new Text(value)));
stringTable.Save();
}

return index;
}

private Cell InsertCellInWorksheet(Worksheet ws, string addressName)
{
SheetData sheetData = ws.GetFirstChild<SheetData>();
Cell cell = null;

UInt32 rowNumber = GetRowIndex(addressName);
Row row = GetRow(sheetData, rowNumber);

// If the cell you need already exists, return it.
// If there is not a cell with the specified column name, insert one.
Cell refCell = row.Elements<Cell>().
Where(c => c.CellReference.Value == addressName).FirstOrDefault();
if (refCell != null)
{
cell = refCell;
}
else
{
cell = CreateCell(row, addressName);
}
return cell;
}

// Add a cell with the specified address to a row.
private Cell CreateCell(Row row, String address)
{
Cell cellResult;
Cell refCell = null;

// Cells must be in sequential order according to CellReference.
// Determine where to insert the new cell.
foreach (Cell cell in row.Elements<Cell>())
{
if (string.Compare(cell.CellReference.Value, address, true) > 0)
{
refCell = cell;
break;
}
}

cellResult = new Cell();
cellResult.CellReference = address;

row.InsertBefore(cellResult, refCell);
return cellResult;
}

// Return the row at the specified rowIndex located within
// the sheet data passed in via wsData. If the row does not
// exist, create it.
private Row GetRow(SheetData wsData, UInt32 rowIndex)
{
var row = wsData.Elements<Row>().
Where(r => r.RowIndex.Value == rowIndex).FirstOrDefault();
if (row == null)
{
row = new Row();
row.RowIndex = rowIndex;
wsData.Append(row);
}
return row;
}

// Given an Excel address such as E5 or AB128, GetRowIndex
// parses the address and returns the row index.
private UInt32 GetRowIndex(string address)
{
string rowPart;
UInt32 l;
UInt32 result = 0;

for (int i = 0; i < address.Length; i++)
{
if (UInt32.TryParse(address.Substring(i, 1), out l))
{
rowPart = address.Substring(i, address.Length - i);
if (UInt32.TryParse(rowPart, out l))
{
result = l;
break;
}
}
}
return result;
}
}


Calling example (Console Application):

class Program
{
static void Main(string[] args)
{
new PortfolioReport();
}
}


More info please click the url as below:
http://msdn.microsoft.com/en-us/library/office/hh180830(v=office.14).aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐